﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HalconDotNet;
using System.Diagnostics;
using System.Threading;
using UserControlHelper;
using System.Drawing;
using System.Windows.Forms;
using WHW_NetUtility;
using System.IO;
using Newtonsoft.Json;

namespace MainFrame
{
    public class visionProc
    {
        public static HTuple hv_CameraParameters ;
        public static HTuple hv_CameraZero;
        public static HObject mapObject;
        public static PointF RorateOffset;
        /// <summary>
        /// 用于更新补偿
        /// </summary>
        public static Postion realResurt1;
        /// <summary>
        /// 用于更新补偿
        /// </summary>
        public static Postion realResurt2;
        public static Result_Template Result1 = new Result_Template();
        public static Result_Template Result2 = new Result_Template();
        public static Action<HObject> UpdataImage;
        public static Postion ResultPlate1;
        public static Postion ResultPlate2;
        public static bool isReduce = false;
        public static int reduce_Radius = 1;
        public static HObject srcObject_pos;
        public static HObject srcObject_ckeck;
        public static HObject srcObject_scan;
        static Stopwatch sw_measure = new Stopwatch();
        static AutoResetEvent ARE_measure = new AutoResetEvent(true);
        private static string ImageDir = Application.StartupPath + $"\\saveImage";
        public static void cam1(HObject imagelist)
        {
            try
            {
                displalyInfo.displayInfoMain($"定位相机，图像已采集，开始处理...");
                sw_measure.Restart();
                HOperatorSet.MirrorImage(imagelist, out imagelist, "row");
                //HOperatorSet.GenRectangle1(out HObject rectangle, 0, 550, 3650, 4950);
                //HOperatorSet.ReduceDomain(imagelist, rectangle, out HObject TEMP);
                //HOperatorSet.CropDomain(TEMP, out visionProc.srcObject_pos);
                //HOperatorSet.MapImage(visionProc.srcObject_pos, mapObject, out visionProc.srcObject_pos);
                //HOperatorSet.RotateImage(visionProc.srcObject_pos, out visionProc.srcObject_pos, -90, "constant");
                //HOperatorSet.ChangeRadialDistortionImage(visionProc.srcObject_pos, visionProc.srcObject_pos,
                //                    out visionProc.srcObject_pos, visionProc.hv_CameraParameters, visionProc.hv_CameraZero);
                HOperatorSet.MapImage(imagelist, visionProc.mapObject, out visionProc.srcObject_pos);
            //    visionProc.srcObject_pos = imagelist;
                GlobalVar.imageDisplay1(visionProc.srcObject_pos);
                if (UpdataImage!=null)
                {
                    UpdataImage(visionProc.srcObject_pos);
                }
                //var imgDir = ImageDir + $"\\{curCameraPlate1.ToString()}";
                //Task.Run(() => {
                //    if (!Directory.Exists(imgDir))
                //    {
                //        Directory.CreateDirectory(imgDir);
                //    }
                //    HOperatorSet.WriteImage(visionProc.srcObject_pos, "jpeg", 0, imgDir + $"\\{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff")}.jpeg");
                //});
               

                if (srcObject_pos != null)
                {
                    if (!GlobalVar.IsTwoPos)
                    {
                        visionProcCam(visionProc.srcObject_pos, curCameraPlate1);
                        if(curCameraPlate1==e_CameraPlate.定位相机平台1)
                            displayMain(e_platePro.平台1);
                        if (curCameraPlate1 == e_CameraPlate.定位相机平台2)
                            displayMain(e_platePro.平台2);
                    }
                    else
                    {
                        visionProcCam(visionProc.srcObject_pos, e_CameraPlate.定位相机平台1);
                        visionProcCam(visionProc.srcObject_pos, e_CameraPlate.定位相机平台2);
                        GlobalVar.IsTwoPos = false;
                        displayMain(e_platePro.双平台有);
                    }
                   
                  
                }
                displalyInfo.displayInfoMain($"--- 定位相机图像处理完成，耗时：[ {sw_measure.ElapsedMilliseconds} ] ---");
                //mre_measure.Set();
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("相机1，视觉处理出错：");
                Log4Helper.WriteLog(ex);
                //mre_measure.Set();
            }
        }
        public static void displayMain(e_platePro platePro)
        {
            Task.Run(() =>
            {
                var msg = DateTime.Now.ToString("HH:mm:ss fff") + ":"+Environment.NewLine;
                HObject xld = null;
                HObject crossing = null;
                try
                {
                    var OKPath = ImageDir + "\\PosOK";
                    var NGPath = ImageDir + "\\PosNG";
                    if (!string.IsNullOrEmpty(GlobalVar.motionConfig.dir_PosOK))
                        OKPath = GlobalVar.motionConfig.dir_PosOK;
                    if (!string.IsNullOrEmpty(GlobalVar.motionConfig.dir_PosNG))
                        NGPath = GlobalVar.motionConfig.dir_PosNG;
                    
                    switch (platePro)
                    {
                        case e_platePro.平台1:
                            {
                                if (GlobalVar.e_Camera_Pos1 == e_Camera_Pos.已拍照OK)
                                {
                                    if (crossing == null)
                                        crossing= Crossing_CenterPix1;
                                    else
                                    HOperatorSet.ConcatObj(crossing, Crossing_CenterPix1, out crossing);
                                    msg += e_CameraPlate.定位相机平台1.ToString() + $":X:{ResultPlate1.X.ToString("F02")}Y:{ResultPlate1.Y.ToString("F02")},Angel:{ResultPlate1.Angle.ToString("F02")}";
                                    Task.Run(() => SaveImage(visionProc.srcObject_pos, OKPath));
                                }
                                else
                                    Task.Run(() => SaveImage(visionProc.srcObject_pos, NGPath));

                            }
                            break;
                        case e_platePro.平台2:
                            {
                                if (GlobalVar.e_Camera_Pos2 == e_Camera_Pos.已拍照OK )
                                {
                                    if (crossing == null)
                                        crossing = Crossing_CenterPix2;
                                    else
                                      HOperatorSet.ConcatObj(crossing, Crossing_CenterPix2, out crossing);
                                    msg += e_CameraPlate.定位相机平台2.ToString() + $":X:{ResultPlate2.X.ToString("F02")}Y:{ResultPlate2.Y.ToString("F02")},Angel:{ResultPlate2.Angle.ToString("F02")}";
                                    Task.Run(() => SaveImage(visionProc.srcObject_pos, OKPath));
                                }else
                                    Task.Run(() => SaveImage(visionProc.srcObject_pos, NGPath));
                            }
                            break;
                        case e_platePro.双平台有:
                            {
                                if (GlobalVar.e_Camera_Pos1 == e_Camera_Pos.已拍照OK)
                                {
                                    if (crossing == null)
                                        crossing = Crossing_CenterPix1;
                                    else
                                    HOperatorSet.ConcatObj(crossing, Crossing_CenterPix1, out crossing);
                                    msg += e_CameraPlate.定位相机平台1.ToString() + $":X:{ResultPlate1.X.ToString("F02")}Y:{ResultPlate1.Y.ToString("F02")},Angel:{ResultPlate1.Angle.ToString("F02")}";
                                }
                                if (GlobalVar.e_Camera_Pos2 == e_Camera_Pos.已拍照OK)
                                {
                                    if (crossing == null)
                                        crossing = Crossing_CenterPix2;
                                    else
                                    HOperatorSet.ConcatObj(crossing, Crossing_CenterPix2, out crossing);
                                    msg +=Environment.NewLine+ e_CameraPlate.定位相机平台2.ToString() + $":X:{ResultPlate2.X.ToString("F02")}Y:{ResultPlate2.Y.ToString("F02")},Angel:{ResultPlate2.Angle.ToString("F02")}";
                                }
                               if(GlobalVar.e_Camera_Pos1==e_Camera_Pos.已拍照OK&&GlobalVar.e_Camera_Pos2== e_Camera_Pos.已拍照OK)
                                {
                                    Task.Run(() => SaveImage(visionProc.srcObject_pos, OKPath));
                                }else
                                {
                                    Task.Run(() => SaveImage(visionProc.srcObject_pos, NGPath));
                                }
                            }
                            break;
                    }
                    GlobalVar.curResult_Pos = new ImageReult { sourceImage = visionProc.srcObject_pos, crossing = crossing, msg = msg,tempxld=xld };
                    GlobalVar.imageDisplayResult_Last();
                    GlobalVar.imageDisplayResult_cur();
                    GlobalVar.DisplayResult_cur();
                }
                catch (Exception ex)
                {

                }
            });
        }
        public static void SaveScanImage(e_platePro platePro)
        {
                try
                {
                var OKPath = ImageDir + "\\WordOK";
                var NGPath = ImageDir + "\\WordNG";
                if (!string.IsNullOrEmpty(GlobalVar.motionConfig.dir_ScanOK) &&!string.IsNullOrEmpty(GlobalVar.motionConfig.dir_ScanNG))
                {
                    OKPath = GlobalVar.motionConfig.dir_ScanOK;
                    NGPath = GlobalVar.motionConfig.dir_ScanNG;
                }
                switch (platePro)
                    {
                        case e_platePro.平台1:
                            {
                                if (GlobalVar.e_Camera_Word1 == e_Camera_Pos.已拍照OK)
                                {
                                    //if (crossing == null)
                                    //    crossing = new HObject();
                                    //HOperatorSet.ConcatObj(crossing, Crossing_CenterPix1, out crossing);
                                    //msg += e_CameraPlate.定位相机平台1.ToString() + $":X:{ResultPlate1.X}Y:{ResultPlate1.Y},Angel:{ResultPlate1.Angle}";
                                    Task.Run(() => SaveImage(visionProc.srcObject_scan, OKPath));
                                }
                                else
                                    Task.Run(() => SaveImage(visionProc.srcObject_scan, NGPath));

                            }
                            break;
                        case e_platePro.平台2:
                            {
                                if (GlobalVar.e_Camera_Word2 == e_Camera_Pos.已拍照OK)
                                {
                                    //if (crossing == null)
                                    //    crossing = new HObject();
                                    //HOperatorSet.ConcatObj(crossing, Crossing_CenterPix2, out crossing);
                                    //msg += e_CameraPlate.定位相机平台2.ToString() + $":X:{ResultPlate2.X}Y:{ResultPlate2.Y},Angel:{ResultPlate2.Angle}";
                                    Task.Run(() => SaveImage(visionProc.srcObject_scan, OKPath));
                                }
                                else
                                    Task.Run(() => SaveImage(visionProc.srcObject_scan, NGPath));
                            }
                            break;
                        case e_platePro.双平台有:
                            {
                                //if (GlobalVar.e_Camera_Word1 == e_Camera_Pos.已拍照OK)
                                //{
                                //    if (crossing == null)
                                //        crossing = new HObject();
                                //    HOperatorSet.ConcatObj(crossing, Crossing_CenterPix1, out crossing);
                                //    msg += e_CameraPlate.定位相机平台1.ToString() + $":X:{ResultPlate1.X}Y:{ResultPlate1.Y},Angel:{ResultPlate1.Angle}";
                                //}
                                //if (GlobalVar.e_Camera_Word2 == e_Camera_Pos.已拍照OK)
                                //{
                                //    if (crossing == null)
                                //        crossing = new HObject();
                                //    HOperatorSet.ConcatObj(crossing, Crossing_CenterPix2, out crossing);
                                //    msg += e_CameraPlate.定位相机平台2.ToString() + $":X:{ResultPlate2.X}Y:{ResultPlate2.Y},Angel:{ResultPlate2.Angle}";
                                //}
                                if (GlobalVar.e_Camera_Word1 == e_Camera_Pos.已拍照OK && GlobalVar.e_Camera_Word2 == e_Camera_Pos.已拍照OK)
                                {
                                    Task.Run(() => SaveImage(visionProc.srcObject_scan, OKPath));
                                }
                                else
                                {
                                    Task.Run(() => SaveImage(visionProc.srcObject_scan, NGPath));
                                }
                            }
                            break;
                    }
                  
                }
                catch (Exception ex)
                {

                }
        }
        public static void SaveCheckImage(e_platePro platePro,string str_cut)
        {
            try
            {

                var OKPath = ImageDir + "\\CheckOK";
                var NGPath = ImageDir + "\\CheckNG";
                if (!string.IsNullOrEmpty(GlobalVar.motionConfig.dir_CheckNG) && !string.IsNullOrEmpty(GlobalVar.motionConfig.dir_CheckOK))
                {
                    OKPath = GlobalVar.motionConfig.dir_CheckOK;
                    NGPath = GlobalVar.motionConfig.dir_CheckNG;
                }
                if (str_cut == "cut")
                {
                    OKPath = ImageDir + "\\CutOK"; ;
                    NGPath = ImageDir + "\\CutNG"; ;
                }

                switch (platePro)
                {
                    case e_platePro.平台1:
                        {
                            if (str_cut == "cut")
                            {
                                if (GlobalVar.e_Camera_Cut1 == e_Camera_Pos.已拍照OK)
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, OKPath));
                                else
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, NGPath));
                            }
                            else
                            {
                                if (GlobalVar.e_Camera_Check1 == e_Camera_Pos.已拍照OK)
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, OKPath));
                                else
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, NGPath));
                            }
                        }
                        break;
                    case e_platePro.平台2:
                        {
                            if (str_cut == "cut")
                            {
                                if (GlobalVar.e_Camera_Cut2 == e_Camera_Pos.已拍照OK)
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, OKPath));
                                else
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, NGPath));
                            }
                            else
                            {
                                if (GlobalVar.e_Camera_Check2 == e_Camera_Pos.已拍照OK)
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, OKPath));
                                else
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, NGPath));
                            }
                        }
                        break;
                    case e_platePro.双平台有:
                        {
                            if (str_cut == "cut")
                            {
                                if (GlobalVar.e_Camera_Cut1 == e_Camera_Pos.已拍照OK && GlobalVar.e_Camera_Cut2 == e_Camera_Pos.已拍照OK)
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, OKPath));
                                else
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, NGPath));
                            }
                            else
                            {
                                if (GlobalVar.e_Camera_Check1 == e_Camera_Pos.已拍照OK && GlobalVar.e_Camera_Check2 == e_Camera_Pos.已拍照OK)
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, OKPath));
                                else
                                    Task.Run(() => SaveImage(visionProc.srcObject_ckeck, NGPath));
                            }
                        }
                        break;
                }

            }
            catch (Exception ex)
                {

                }
         
        }
        public static object lockImage = new object();
        public static void SaveImage(HObject imageHobject,string dir)
        {
            try
            {
                lock(lockImage)
                {
                    if (!string.IsNullOrEmpty(dir))
                    {
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                        Task.Run(new Action(() =>
                        {
                            try
                            {
                                DirectoryInfo dif = new DirectoryInfo(dir);
                                if (dif.GetFiles().Count() > 50)
                                {
                                    int iii = 0;
                                    foreach (var item in dif.GetFiles())
                                    {
                                        try
                                        {
                                            if ((iii) < 15)
                                            {
                                                iii++;
                                                File.Delete(item.FullName);
                                            }
                                        }
                                        catch (Exception) { }
                                    }
                                }
                            }
                            catch (Exception) { }
                        }));

                        HOperatorSet.WriteImage(imageHobject, "png", 0, dir + $"\\{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff")}.png");
                    }
                }
             
            
            }catch(Exception ex)
            {
                displalyInfo.displayInfoMain(ex.Message);
            }
          
        }
        public static void cam2(HObject imagelist)
        {
            try
            {
                displalyInfo.displayInfoMain($"图案相机，图像已采集，开始处理...");

                srcObject_scan = imagelist;
                GlobalVar.imageDisplay2(srcObject_scan);
                if (UpdataImage != null)
                {
                    UpdataImage(imagelist);
                }
                //var imgDir = ImageDir  + $"\\{curCameraPlate2.ToString()}";
                //if (!Directory.Exists(imgDir))
                //{
                //    Directory.CreateDirectory(imgDir);
                //}
                //HOperatorSet.WriteImage(srcObject_scan, "jpeg", 0, imgDir + $"\\{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff")}.jpeg");
                sw_measure.Restart();
                if (srcObject_scan != null)
                {
                    visionProcCam(srcObject_scan, curCameraPlate2);
                    if (curCameraPlate2 == e_CameraPlate.图案相机平台1)
                      Task.Run( ()=> SaveScanImage(e_platePro.平台1));
                    else
                        Task.Run(() => SaveScanImage(e_platePro.平台2));
                }
                displalyInfo.displayInfoMain($"--- 图案相机图像处理完成，耗时：[ {sw_measure.ElapsedMilliseconds} ] ---");
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("图案相机，视觉处理出错：");
                Log4Helper.WriteLog(ex);
                //mre_measure.Set();
            }
        }

        public static int CamIdx = 10;
        public static void cam3(HObject imagelist)
        {
            try
            {
                srcObject_ckeck = imagelist;
                displalyInfo.displayInfoMain($"检测相机，图像已采集，开始处理...");
                //对图像进行旋转处理
                if (UpdataImage != null)
                {
                    UpdataImage(imagelist);
                }
                GlobalVar.imageDisplay3(srcObject_ckeck);
                //var imgDir = ImageDir + $"\\{curCameraPlate3.ToString()}";
                //if (!Directory.Exists(imgDir))
                //{
                //    Directory.CreateDirectory(imgDir);
                //}
                //HOperatorSet.WriteImage(srcObject_ckeck, "jpeg", 0, imgDir + $"\\{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff")}.jpeg");
                sw_measure.Restart();
                if (imagelist != null)
                {
                    if (GlobalVar.IsLabelPosTwo || GlobalVar.IsCheckTwo)
                    {
                        GlobalVar.imageDisplay3(srcObject_ckeck);
                        if (CamIdx==1)
                        {
                            visionProcCam(srcObject_ckeck, e_CameraPlate.检测相机平台1);
                            CamIdx = 10;
                        }
                        else if((CamIdx == 2))
                        {
                            visionProcCam(srcObject_ckeck, e_CameraPlate.检测相机平台2);
                            CamIdx = 10;
                        }
                        else
                        {
                            visionProcCam(srcObject_ckeck, e_CameraPlate.检测相机平台1);
                            visionProcCam(srcObject_ckeck, e_CameraPlate.检测相机平台2);
                        }
                        
                        if(GlobalVar.IsPosBeforeLabel)
                        {
                            Task.Run(() => SaveCheckImage(e_platePro.双平台有,"cut"));
                        }else
                        {
                            Task.Run(() => SaveCheckImage(e_platePro.双平台有, "check"));
                        }
                        GlobalVar.IsLabelPosTwo = false;
                        GlobalVar.IsCheckTwo = false;
                        GlobalVar.IsPosBeforeLabel = false;
                     
                    }
                    else
                    {
                        visionProcCam(srcObject_ckeck, curCameraPlate3);
                        if (GlobalVar.IsPosBeforeLabel)
                        {
                            if (curCameraPlate3 == e_CameraPlate.检测相机平台1)
                                Task.Run(() => SaveCheckImage(e_platePro.平台1,"cut"));
                            else
                                Task.Run(() => SaveCheckImage(e_platePro.平台2, "cut"));
                        }else
                        {
                            if (curCameraPlate3 == e_CameraPlate.检测相机平台1)
                                Task.Run(() => SaveCheckImage(e_platePro.平台1, "check"));
                            else
                                Task.Run(() => SaveCheckImage(e_platePro.平台2, "check"));
                        }
                        
                        GlobalVar.IsPosBeforeLabel = false;
                    }
                }
                displalyInfo.displayInfoMain($"--- 检测相机图像处理完成，耗时：[ {sw_measure.ElapsedMilliseconds} ] ---");
                //mre_measure.Set();
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("检测相机，视觉处理出错：");
                Log4Helper.WriteLog(ex);
                //mre_measure.Set();
            }

        }
        public static void scale_image_range(HObject ho_Image, out HObject ho_ImageScaled, HTuple hv_Min, HTuple hv_Max)
        {
            HObject[] OTemp = new HObject[20];
            HObject ho_ImageSelected = null, ho_SelectedChannel = null;
            HObject ho_LowerRegion = null, ho_UpperRegion = null, ho_ImageSelectedScaled = null;
            // Local copy input parameter variables 
            HObject ho_Image_COPY_INP_TMP;
            ho_Image_COPY_INP_TMP = new HObject(ho_Image);
            HTuple hv_LowerLimit = new HTuple(), hv_UpperLimit = new HTuple();
            HTuple hv_Mult = new HTuple(), hv_Add = new HTuple(), hv_NumImages = new HTuple();
            HTuple hv_ImageIndex = new HTuple(), hv_Channels = new HTuple();
            HTuple hv_ChannelIndex = new HTuple(), hv_MinGray = new HTuple();
            HTuple hv_MaxGray = new HTuple(), hv_Range = new HTuple();
            HTuple hv_Max_COPY_INP_TMP = new HTuple(hv_Max);
            HTuple hv_Min_COPY_INP_TMP = new HTuple(hv_Min);
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_ImageScaled);
            HOperatorSet.GenEmptyObj(out ho_ImageSelected);
            HOperatorSet.GenEmptyObj(out ho_SelectedChannel);
            HOperatorSet.GenEmptyObj(out ho_LowerRegion);
            HOperatorSet.GenEmptyObj(out ho_UpperRegion);
            HOperatorSet.GenEmptyObj(out ho_ImageSelectedScaled);
            if ((int)(new HTuple((new HTuple(hv_Min_COPY_INP_TMP.TupleLength())).TupleEqual(
                2))) != 0)
            {

                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    hv_LowerLimit = hv_Min_COPY_INP_TMP.TupleSelect(
                        1);
                }
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    {
                        HTuple
                          ExpTmpLocalVar_Min = hv_Min_COPY_INP_TMP.TupleSelect(
                            0);

                        hv_Min_COPY_INP_TMP = ExpTmpLocalVar_Min;
                    }
                }
            }
            else
            {

                hv_LowerLimit = 0.0;
            }
            if ((int)(new HTuple((new HTuple(hv_Max_COPY_INP_TMP.TupleLength())).TupleEqual(
                2))) != 0)
            {

                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    hv_UpperLimit = hv_Max_COPY_INP_TMP.TupleSelect(
                        1);
                }
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    {
                        HTuple
                          ExpTmpLocalVar_Max = hv_Max_COPY_INP_TMP.TupleSelect(
                            0);
                        hv_Max_COPY_INP_TMP = ExpTmpLocalVar_Max;
                    }
                }
            }
            else
            {
                hv_UpperLimit = 255.0;
            }
            //
            //Calculate scaling parameters.
            //Only scale if the scaling range is not zero.
            if ((int)((new HTuple(((((hv_Max_COPY_INP_TMP - hv_Min_COPY_INP_TMP)).TupleAbs()
                )).TupleLess(1.0E-6))).TupleNot()) != 0)
            {
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    hv_Mult = (((hv_UpperLimit - hv_LowerLimit)).TupleReal()
                        ) / (hv_Max_COPY_INP_TMP - hv_Min_COPY_INP_TMP);
                }
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    hv_Add = ((-hv_Mult) * hv_Min_COPY_INP_TMP) + hv_LowerLimit;
                }
                {
                    HObject ExpTmpOutVar_0;
                    HOperatorSet.ScaleImage(ho_Image_COPY_INP_TMP, out ExpTmpOutVar_0, hv_Mult,
                        hv_Add);
                    ho_Image_COPY_INP_TMP.Dispose();
                    ho_Image_COPY_INP_TMP = ExpTmpOutVar_0;
                }
            }
            HOperatorSet.GenEmptyObj(out ho_ImageScaled);
            HOperatorSet.CountObj(ho_Image_COPY_INP_TMP, out hv_NumImages);
            HTuple end_val51 = hv_NumImages;
            HTuple step_val51 = 1;
            for (hv_ImageIndex = 1; hv_ImageIndex.Continue(end_val51, step_val51); hv_ImageIndex = hv_ImageIndex.TupleAdd(step_val51))
            {
                HOperatorSet.SelectObj(ho_Image_COPY_INP_TMP, out ho_ImageSelected, hv_ImageIndex);

                HOperatorSet.CountChannels(ho_ImageSelected, out hv_Channels);
                HTuple end_val54 = hv_Channels;
                HTuple step_val54 = 1;
                for (hv_ChannelIndex = 1; hv_ChannelIndex.Continue(end_val54, step_val54); hv_ChannelIndex = hv_ChannelIndex.TupleAdd(step_val54))
                {
                    HOperatorSet.AccessChannel(ho_ImageSelected, out ho_SelectedChannel, hv_ChannelIndex);
                    HOperatorSet.MinMaxGray(ho_SelectedChannel, ho_SelectedChannel, 0, out hv_MinGray,
                        out hv_MaxGray, out hv_Range);
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        HOperatorSet.Threshold(ho_SelectedChannel, out ho_LowerRegion, ((hv_MinGray.TupleConcat(
                            hv_LowerLimit))).TupleMin(), hv_LowerLimit);
                    }
                    using (HDevDisposeHelper dh = new HDevDisposeHelper())
                    {
                        HOperatorSet.Threshold(ho_SelectedChannel, out ho_UpperRegion, hv_UpperLimit,
                            ((hv_UpperLimit.TupleConcat(hv_MaxGray))).TupleMax());
                    }
                    {
                        HObject ExpTmpOutVar_0;
                        HOperatorSet.PaintRegion(ho_LowerRegion, ho_SelectedChannel, out ExpTmpOutVar_0,
                            hv_LowerLimit, "fill");
                        ho_SelectedChannel = ExpTmpOutVar_0;
                    }
                    {
                        HObject ExpTmpOutVar_0;
                        HOperatorSet.PaintRegion(ho_UpperRegion, ho_SelectedChannel, out ExpTmpOutVar_0,
                            hv_UpperLimit, "fill");
                        ho_SelectedChannel = ExpTmpOutVar_0;
                    }
                    if ((int)(new HTuple(hv_ChannelIndex.TupleEqual(1))) != 0)
                    {
                        HOperatorSet.CopyObj(ho_SelectedChannel, out ho_ImageSelectedScaled, 1,
                            1);
                    }
                    else
                    {
                        {
                            HObject ExpTmpOutVar_0;
                            HOperatorSet.AppendChannel(ho_ImageSelectedScaled, ho_SelectedChannel,
                                out ExpTmpOutVar_0);
                            ho_ImageSelectedScaled = ExpTmpOutVar_0;
                        }
                    }
                }
                {
                    HObject ExpTmpOutVar_0;
                    HOperatorSet.ConcatObj(ho_ImageScaled, ho_ImageSelectedScaled, out ExpTmpOutVar_0
                        );
                    ho_ImageScaled = ExpTmpOutVar_0;
                }
            }

            return;
        }
        public static Postion LabelPostion1;
        public static Postion LabelPostion2;
        public static e_CameraPlate curCameraPlate1 = e_CameraPlate.定位相机平台1;
        public static e_CameraPlate curCameraPlate2 = e_CameraPlate.图案相机平台1;
        public static e_CameraPlate curCameraPlate3 = e_CameraPlate.检测相机平台1;
        public static List<ROIRegion> ROI_List;
        public static List<HObject> ROI_M_List1;
        public static List<HObject> ROI_M_List2;
        public static List<HTuple> TemplateIds;
        public static List<HObject> Template_xlds;
        public static AbsPostion pos1pix;
        public static AbsPostion pos2pix;

        public static Postion BasePostion1;
        public static Postion BasePostion2;
        public static HObject ReadImage(string path)
        {
            try
            {
                HOperatorSet.ReadImage(out HObject hobj_Image, path);
                return hobj_Image;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static string AllArea = "";
        /// <summary>
        /// 
        /// </summary>
        /// <param name="hoImage"></param>
        /// <param name="camIndex">0,扫码相机  1定位相机</param>
        /// <param name="index">平台1  平台2</param>
        public static void visionProcCam(HObject hoImage, e_CameraPlate cameraPlate)
        {
            try
            {
                switch (cameraPlate)
                {
                    case e_CameraPlate.定位相机平台1:
                        {
                            visionProc.ROI1 = visionProc.ROI_List[(int)cameraPlate];

                            var Temp_parama = GlobalVar.motionConfig.TF_list[(int)e_CameraPlate.定位相机平台1];
                            Result1 = findTemplate(hoImage, visionProc.TemplateIds[(int)e_CameraPlate.定位相机平台1], Temp_parama, visionProc.ROI1.ROI_Region);
                            if (Result1 != null)
                            {
                                if (GlobalVar.motionConfig.IsEnableLinePos)
                                {
                                    var lineResult = findLine(hoImage, GlobalVar.motionConfig.PosLindFind1[0], Result1, visionProc.ROI1.ROI_Postion);
                                    var lineResult2 = findLine(hoImage, GlobalVar.motionConfig.PosLindFind1[1], Result1, visionProc.ROI1.ROI_Postion2);
                                    var pos = visionProc.intersection_Line(lineResult, lineResult2);
                                    if (pos != null)
                                    {
                                        Result1.dAngle = pos.R;
                                        Result1.dColumn = pos.X;
                                        Result1.dRow = pos.Y;
                                    }
                                    else
                                    {
                                        Result1 = null;
                                        GlobalVar.e_Camera_Pos1 = e_Camera_Pos.已拍照NG;
                                        GlobalVar.IsProccessed1 = true;
                                        break;
                                    }
                                }
 
                                GlobalVar.imageDisplay1_obj(visionProc.ROI_List[(int)cameraPlate].ROI_Region, "green");
                                HOperatorSet.GenCrossContourXld(out HObject crosing, Result1.dRow, Result1.dColumn, 200, Result1.dAngle);
                                GlobalVar.imageDisplay1_obj(crosing, "red");
                                displalyInfo.displayInfoMain($"X:{Result1.dColumn},Y:{Result1.dRow},R:{Result1.dAngle},百分比:{Result1.dScore}");
                                var curVision = GlobalVar.userConfig.PlateVisionList[(int)e_CameraPlate.定位相机平台1];
                                var curPos = new Postion()
                                {
                                    Angle = Result1.dAngle * 180 / Math.PI + GlobalVar.motionConfig.visionCenter1.R,
                                    X = Result1.dColumn,
                                    Y = Result1.dRow,
                                    xMax = curVision.Xmax,
                                    yMax = curVision.Ymax,
                                    xMin = curVision.Xmin,
                                    yMin = curVision.Ymin,
                                    rMin = curVision.Rmin,
                                    rMax = curVision.Rmax,
                                };

                                curPos.Angle = Math.Round(curPos.Angle, 2);
                                var scanPos = GlobalVar.motionConfig.Plate1_pos[(int)e_Pos.拍照位];
                                var realResurt = CalibratePostion(curPos, curVision, new PointF() { X = (float)scanPos.X, Y = (float)scanPos.Y },
                                    GlobalVar.motionConfig.visionCenter1,GlobalVar.motionConfig.visionBase1);
                                if (realResurt != null)
                                {
                                    if (realResurt.Angle > 180)
                                        realResurt.Angle = realResurt.Angle - 360;
                                    displalyInfo.displayInfoMain($"机器坐标X:{realResurt.X},机器坐标Y:{realResurt.Y},机器坐标R:{realResurt.Angle}");
                                    var putPos = GlobalVar.motionConfig.Plate1_pos[(int)e_Pos.OK放标位];
                                    var resPos = visionProc.TransPoint(realResurt, GlobalVar.userConfig.PlateVisionList[(int)e_CameraPlate.定位相机平台1], 
                                        scanPos, putPos, GlobalVar.motionConfig.visionPutOK1);
                                    if (CPos != null)
                                    {
                                        realResurt1 = new Postion() { X = CPos.X, Y = CPos.Y, Angle = CPos.Angle };
                                    }
                                    displalyInfo.displayInfoMain($"{cameraPlate.ToString()}发送X:{resPos.X},发送Y:{resPos.Y},发送R:{resPos.Angle}");
                                   if (resPos.X > Temp_parama.xMax || resPos.X < Temp_parama.xMin || 
                                        resPos.Y > Temp_parama.yMax || resPos.Y < Temp_parama.yMin || 
                                        resPos.Angle > Temp_parama.rMax || resPos.Angle < Temp_parama.rMin)
                                    {
                                        displalyInfo.displayInfoMain($"{cameraPlate.ToString()}补偿超范围  NG处理");
                                        GlobalVar.e_Camera_Pos1 = e_Camera_Pos.已拍照NG;
                                    }
                                    else
                                    {
                                        curPos.X = resPos.X;
                                        curPos.Y = resPos.Y;
                                        curPos.Angle = resPos.Angle;
                                        ResultPlate1 = curPos;
                                        GlobalVar.e_Camera_Pos1 = e_Camera_Pos.已拍照OK;
                                    }
                                    ResultPlate1 = resPos;
                                }
                                else
                                {
                                    GlobalVar.e_Camera_Pos1 = e_Camera_Pos.已拍照NG;

                                }
                            }
                            else
                            {
                                GlobalVar.e_Camera_Pos1 = e_Camera_Pos.已拍照NG;

                            }
                            GlobalVar.IsProccessed1 = true;
                        }
                        break;
                    case e_CameraPlate.定位相机平台2:
                        {
                            visionProc.ROI1 = visionProc.ROI_List[(int)cameraPlate];
                            var Temp_parama = GlobalVar.motionConfig.TF_list[(int)e_CameraPlate.定位相机平台2];
                            Result2 = findTemplate(hoImage, visionProc.TemplateIds[(int)e_CameraPlate.定位相机平台2], Temp_parama, visionProc.ROI1.ROI_Region);
                            if (Result2 != null)
                            {
                                var curVision = GlobalVar.userConfig.PlateVisionList[(int)e_CameraPlate.定位相机平台2];
                                if (GlobalVar.motionConfig.IsEnableLinePos)
                                {
                                    var lineResult = findLine(hoImage, GlobalVar.motionConfig.PosLindFind2[0], Result2, visionProc.ROI1.ROI_Postion);
                                    var lineResult2 = findLine(hoImage, GlobalVar.motionConfig.PosLindFind2[1], Result2, visionProc.ROI1.ROI_Postion2);
                                    var pos = visionProc.intersection_Line(lineResult, lineResult2);
                                    if (pos != null)
                                    {
                                        Result2.dAngle = pos.R;
                                        Result2.dColumn = pos.X;
                                        Result2.dRow = pos.Y;
                                    }
                                    else
                                    {
                                        Result2 = null;
                                        GlobalVar.e_Camera_Pos2 = e_Camera_Pos.已拍照NG;
                                        GlobalVar.IsProccessed2 = true;
                                        break;
                                    }
                                }

                                GlobalVar.imageDisplay1_obj(visionProc.ROI_List[(int)cameraPlate].ROI_Region, "green");
                                HOperatorSet.GenCrossContourXld(out HObject crosing, Result2.dRow, Result2.dColumn, 200, Result2.dAngle);
                                GlobalVar.imageDisplay1_obj(crosing, "red");
                                displalyInfo.displayInfoMain($"X:{Result2.dColumn},Y:{Result2.dRow},R:{Result2.dAngle / Math.PI * 180},百分比:{Result2.dScore}");
                               
                                var curPos = new Postion()
                                {
                                    Angle = Result2.dAngle * 180 / Math.PI + GlobalVar.motionConfig.visionCenter2.R,
                                    X = Result2.dColumn,
                                    Y = Result2.dRow,
                                    xMax = curVision.Xmax,
                                    yMax = curVision.Ymax,
                                    xMin = curVision.Xmin,
                                    yMin = curVision.Ymin,
                                    rMax = curVision.Rmax,
                                    rMin = curVision.Rmin,
                                };
                                curPos.Angle = Math.Round(curPos.Angle, 2);
                                var scanPos = GlobalVar.motionConfig.Plate2_pos[(int)e_Pos.拍照位];
                                var realResurt = CalibratePostion2(curPos, curVision, new PointF() { X = (float)scanPos.X, Y = (float)scanPos.Y },GlobalVar.motionConfig.visionCenter2, GlobalVar.motionConfig.visionBase2);
                                if (realResurt != null)
                                {
                                    if (realResurt.Angle > 180)
                                        realResurt.Angle = realResurt.Angle - 360;
                                    displalyInfo.displayInfoMain($"机器坐标X:{realResurt.X},机器坐标Y:{realResurt.Y},机器坐标R:{realResurt.Angle}");
                                    var putPos = GlobalVar.motionConfig.Plate2_pos[(int)e_Pos.OK放标位];
                                    var resPos = visionProc.TransPoint(realResurt, GlobalVar.userConfig.PlateVisionList[(int)e_CameraPlate.定位相机平台2], scanPos, putPos, GlobalVar.motionConfig.visionPutOK2);
                                    if (CPos != null)
                                    {
                                        realResurt2 = new Postion() { X = CPos.X, Y = CPos.Y, Angle = CPos.Angle };
                                    }
                                    displalyInfo.displayInfoMain($"{cameraPlate.ToString()}发送X:{resPos.X},发送Y:{resPos.Y},发送R:{resPos.Angle}");

                                 if (resPos.X > Temp_parama.xMax || resPos.X < Temp_parama.xMin || resPos.Y > Temp_parama.yMax || resPos.Y < Temp_parama.yMin || resPos.Angle > Temp_parama.rMax || resPos.Angle < Temp_parama.rMin)
                                 //       if (resPos.X > curPos.xMax || resPos.X < curPos.xMin || resPos.Y > curPos.yMax || resPos.Y < curPos.yMin || resPos.Angle > curPos.rMax || resPos.Angle < curPos.rMin)
                                    {
                                        displalyInfo.displayInfoMain($"{cameraPlate.ToString()}补偿超范围  NG处理");
                                        GlobalVar.e_Camera_Pos2 = e_Camera_Pos.已拍照NG;
                                    }
                                    else
                                    {
                                        curPos.X = resPos.X;
                                        curPos.Y = resPos.Y;
                                        curPos.Angle = resPos.Angle;
                                        ResultPlate2 = curPos;
                                        GlobalVar.e_Camera_Pos2 = e_Camera_Pos.已拍照OK;
                                    }
                                    ResultPlate2 = resPos;

                                }
                                else
                                {
                                    GlobalVar.e_Camera_Pos2 = e_Camera_Pos.已拍照NG;

                                }
                            }
                            else
                            {
                                GlobalVar.e_Camera_Pos2 = e_Camera_Pos.已拍照NG;

                            }
                            GlobalVar.IsProccessed2 = true;
                        }
                        break;
                    case e_CameraPlate.图案相机平台1:
                        {
                            HOperatorSet.ReduceDomain(hoImage, visionProc.ROI_List[(int)e_CameraPlate.图案相机平台1].ROI_Region, out HObject region_cut);
                            HOperatorSet.Threshold(region_cut, out HObject AreaHobj, GlobalVar.motionConfig.draw1.d_grayMin, GlobalVar.motionConfig.draw1.d_grayMax);
                            HOperatorSet.AreaCenter(AreaHobj, out HTuple hArea,out HTuple tempR, out HTuple tempC);
                            if(hArea.Type!=HTupleType.EMPTY)
                            {
                                displalyInfo.displayInfoMain("图案相机平台1面积:" + hArea.L.ToString());
                                if (hArea.L>= GlobalVar.motionConfig.draw1.d_AreaMin&& hArea.L <= GlobalVar.motionConfig.draw1.d_AreaMax)
                                {
                                    var ResultTemp = findTemplate(hoImage, visionProc.TemplateIds[(int)e_CameraPlate.图案相机平台1], GlobalVar.motionConfig.TF_list[(int)e_CameraPlate.图案相机平台1], visionProc.ROI_List[(int)e_CameraPlate.图案相机平台1].ROI_Region);
                                    if (ResultTemp != null)
                                    {
                                        GlobalVar.imageDisplay2_obj(visionProc.ROI_List[(int)e_CameraPlate.图案相机平台1].ROI_Region, "green");
                                        HOperatorSet.GenCrossContourXld(out HObject crosing, ResultTemp.dRow, ResultTemp.dColumn, 200, ResultTemp.dAngle);
                                        GlobalVar.imageDisplay2_obj(crosing, "red");
                                        displalyInfo.displayInfoMain("图案相机平台1:" + JsonConvert.SerializeObject(ResultTemp)+$"面积为{hArea.L}");
                                        GlobalVar.e_Camera_Word1 = e_Camera_Pos.已拍照OK;
                                    }
                                }else
                                {
                                    //GlobalVar.isFlyingWithoutWord1 = true;
                                    GlobalVar.e_Camera_Word1 = e_Camera_Pos.已拍照NG;
                                }
                            }else
                            {
                               // GlobalVar.isFlyingWithoutWord1 = true;
                                GlobalVar.e_Camera_Word1 = e_Camera_Pos.已拍照NG;
                            }
                          
                        }
                        break;
                    case e_CameraPlate.图案相机平台2:
                        {

                            HOperatorSet.ReduceDomain(hoImage, visionProc.ROI_List[(int)e_CameraPlate.图案相机平台2].ROI_Region, out HObject region_cut);
                            HOperatorSet.Threshold(region_cut, out HObject AreaHobj, GlobalVar.motionConfig.draw2.d_grayMin, GlobalVar.motionConfig.draw2.d_grayMax);
                            HOperatorSet.AreaCenter(AreaHobj, out HTuple hArea, out HTuple tempR, out HTuple tempC);
                            if (hArea.Type != HTupleType.EMPTY)
                            {
                                displalyInfo.displayInfoMain("图案相机平台2面积:" + hArea.L.ToString());
                                if (hArea.L >= GlobalVar.motionConfig.draw2.d_AreaMin && hArea.L <= GlobalVar.motionConfig.draw2.d_AreaMax)
                                {
                                
                                    var ResultTemp = findTemplate(hoImage, visionProc.TemplateIds[(int)e_CameraPlate.图案相机平台2], GlobalVar.motionConfig.TF_list[(int)e_CameraPlate.图案相机平台2], visionProc.ROI_List[(int)e_CameraPlate.图案相机平台2].ROI_Region);
                                    if (ResultTemp != null)
                                    {
                                        GlobalVar.imageDisplay2_obj(visionProc.ROI_List[(int)e_CameraPlate.图案相机平台2].ROI_Region, "green");
                                        HOperatorSet.GenCrossContourXld(out HObject crosing, ResultTemp.dRow, ResultTemp.dColumn, 200, ResultTemp.dAngle);
                                        GlobalVar.imageDisplay2_obj(crosing, "red");

                                        displalyInfo.displayInfoMain("图案相机平台2:" + JsonConvert.SerializeObject(ResultTemp));
                                        GlobalVar.e_Camera_Word2 = e_Camera_Pos.已拍照OK;
                                    }
                                }
                                else
                                {
                               //     GlobalVar.isFlyingWithoutWord2 = true;
                                    GlobalVar.e_Camera_Word2 = e_Camera_Pos.已拍照NG;
                                }
                            }
                            else
                            {
                            //    GlobalVar.isFlyingWithoutWord2 = true;
                                GlobalVar.e_Camera_Word2 = e_Camera_Pos.已拍照NG;
                            }
                        }
                        break;
                    case e_CameraPlate.检测相机平台1:
                        {
                            #region 贴膜前
                            if (GlobalVar.IsPosBeforeLabel)
                            {
                                if (GlobalVar.motionConfig.posAfterLabel != null)
                                {
                                    var parama = GlobalVar.motionConfig.posAfterLabel;
                                    #region 撕膜效果检测
                                    AllArea = "";
                                    if (GlobalVar.userConfig.IsCheckCutResult)
                                    {
                                        //HOperatorSet.ReduceDomain(hoImage, visionProc.ROI_M_List1[(int)e_RegionCheck.撕膜区域1], out HObject cutObj1);
                                        //HOperatorSet.Threshold(cutObj1, out HObject region1, parama.grayMin1, parama.grayMax1);
                                        //HOperatorSet.ClosingCircle(region1, out region1, 3);
                                        //HOperatorSet.OpeningCircle(region1, out region1, 3);
                                        //HOperatorSet.Connection(region1, out region1);
                                        //HOperatorSet.FillUp(region1, out region1);
                                        //HOperatorSet.SelectShapeStd(region1, out region1, "max_area", 70);
                                        //HObject REG1 = visionProc.ROI_M_List1[(int)e_RegionCheck.撕膜区域1];
                                        //GetCutResult(hoImage, REG1,
                                        // parama.grayMin1, parama.grayMax1, out HObject region1);
                                        //HOperatorSet.AreaCenter(region1, out HTuple area1, out HTuple row_Cut1, out HTuple col_Cut1);

                                        //HOperatorSet.ReduceDomain(hoImage, visionProc.ROI_M_List1[(int)e_RegionCheck.撕膜区域2], out HObject cutObj2);
                                        //HOperatorSet.Threshold(cutObj2, out HObject region2, parama.grayMin1, parama.grayMax1);
                                        //HOperatorSet.ClosingCircle(region2, out region2, 3);
                                        //HOperatorSet.OpeningCircle(region2, out region2, 3);
                                        //HOperatorSet.Connection(region2, out region2);
                                        //HOperatorSet.FillUp(region2, out region2);
                                        //HOperatorSet.SelectShapeStd(region2, out region2, "max_area", 70);
                                        //HObject REG2 = visionProc.ROI_M_List1[(int)e_RegionCheck.撕膜区域2];
                                        //GetCutResult(hoImage, REG2,
                                        // parama.grayMin1, parama.grayMax1, out HObject region2);
                                        //HOperatorSet.AreaCenter(region2, out HTuple area2, out HTuple row_Cut2, out HTuple col_Cut2);

                                        //HOperatorSet.ReduceDomain(hoImage, visionProc.ROI_M_List1[(int)e_RegionCheck.撕膜区域3], out HObject cutObj3);
                                        //HOperatorSet.Threshold(cutObj3, out HObject region3, parama.grayMin1, parama.grayMax1);
                                        //HOperatorSet.ClosingCircle(region3, out region3, 3);
                                        //HOperatorSet.OpeningCircle(region3, out region3, 3);
                                        //HOperatorSet.Connection(region3, out region3);
                                        //HOperatorSet.FillUp(region3, out region3);
                                        //HOperatorSet.SelectShapeStd(region3, out region3, "max_area", 70);
                                        //HObject REG3 = visionProc.ROI_M_List1[(int)e_RegionCheck.撕膜区域3];
                                        //GetCutResult(hoImage, REG3,
                                        // parama.grayMin1, parama.grayMax1, out HObject region3);
                                        //HOperatorSet.AreaCenter(region3, out HTuple area3, out HTuple row_Cut3, out HTuple col_Cut3);
                                        HObject Reg1 = visionProc.ROI_M_List1[(int)e_RegionCheck.撕膜区域1];
                                        HObject Reg2 = visionProc.ROI_M_List1[(int)e_RegionCheck.撕膜区域2];
                                        HObject Reg3 = visionProc.ROI_M_List1[(int)e_RegionCheck.撕膜区域3];

                                        HOperatorSet.ReduceDomain(hoImage, Reg1, out HObject cutObj1);
                                        HOperatorSet.Threshold(cutObj1, out HObject region1, parama.grayMin1, parama.grayMax1);
                                        HOperatorSet.Connection(region1, out region1);
                                        HOperatorSet.FillUp(region1, out region1);
                                        HOperatorSet.SelectShapeStd(region1, out region1, "max_area", 70);
                                        HOperatorSet.AreaCenter(region1, out HTuple area1, out HTuple row_Cut1, out HTuple col_Cut1);
                                        HOperatorSet.ReduceDomain(hoImage, Reg2, out HObject cutObj2);
                                        HOperatorSet.Threshold(cutObj2, out HObject region2, parama.grayMin1, parama.grayMax1);
                                        HOperatorSet.Connection(region2, out region2);
                                        HOperatorSet.FillUp(region2, out region2);
                                        HOperatorSet.SelectShapeStd(region2, out region2, "max_area", 70);
                                        HOperatorSet.AreaCenter(region2, out HTuple area2, out HTuple row_Cut2, out HTuple col_Cut2);
                                        HOperatorSet.ReduceDomain(hoImage, Reg3, out HObject cutObj3);
                                        HOperatorSet.Threshold(cutObj3, out HObject region3, parama.grayMin1, parama.grayMax1);
                                        HOperatorSet.Connection(region3, out region3);
                                        HOperatorSet.FillUp(region3, out region3);
                                        HOperatorSet.SelectShapeStd(region3, out region1, "max_area", 70);
                                        HOperatorSet.AreaCenter(region3, out HTuple area3, out HTuple row_Cut3, out HTuple col_Cut3);
                                        if (area1.Type != HTupleType.EMPTY) AllArea += area1.D.ToString();
                                        if (area2.Type != HTupleType.EMPTY) AllArea += "," + area2.D.ToString();
                                        if (area3.Type != HTupleType.EMPTY) AllArea += "," + area3.D.ToString();
                                      
                                        if (area1.Type != HTupleType.EMPTY && area2.Type != HTupleType.EMPTY && area3.Type != HTupleType.EMPTY)
                                        {
                                            var areaLst = new List<double>();
                                            areaLst.Add(area1.D); areaLst.Add(area2.D); areaLst.Add(area3.D);
                                            if (areaLst.Where(a => a >= parama.areaMin1 && a <= parama.areaMax1).Count() > 0)
                                            
                                                GlobalVar.e_Camera_Cut1 = e_Camera_Pos.已拍照NG;
                                            else
                                                GlobalVar.e_Camera_Cut1 = e_Camera_Pos.已拍照OK;
                                            displalyInfo.displayInfoMain("撕膜面积:" + string.Join(",", areaLst));
                                            AllArea = string.Join(",", areaLst);
                                            GlobalVar.imageDisplay3_obj(region1, "red");
                                            GlobalVar.imageDisplay3_obj(region2, "red");
                                            GlobalVar.imageDisplay3_obj(region3, "red");
                                            GlobalVar.imageDisplay3_obj(Reg1, "green");
                                            GlobalVar.imageDisplay3_obj(Reg2, "green");
                                            GlobalVar.imageDisplay3_obj(Reg3, "green");
                                        }
                                        else
                                        {
                                            var str = "撕膜面积";
                                            if (area1.Type != HTupleType.EMPTY) str +="撕膜1面积"+ area1.D.ToString();
                                            if (area2.Type != HTupleType.EMPTY) str += "撕膜2面积" + area2.D.ToString();
                                            if (area3.Type != HTupleType.EMPTY) str += "撕膜3面积" + area3.D.ToString();
                                            displalyInfo.displayInfoMain(str);
                                            GlobalVar.e_Camera_Cut1 = e_Camera_Pos.已拍照OK;
                                        }

                                        
                                        if (!GlobalVar.userConfig.IsPosAfterLabel)
                                            break;
                                    }
                                    #endregion

                                    #region 治具定位
                                    if (GlobalVar.userConfig.IsPosAfterLabel)
                                    {
                                        bool isHavePos = false;
                                        var pos = new VisionPos();
                                        HObject AreaHobj1 = new HObject();
                                        HObject AreaHobj2 = new HObject();
                                        if (GlobalVar.motionConfig.IsEnableCircleCheck)
                                        {
                                            HObject roi1 = visionProc.ROI_M_List1[(int)e_RegionCheck.找圆区域1];
                                            HObject roi2 = visionProc.ROI_M_List1[(int)e_RegionCheck.找圆区域2];

                                            //HOperatorSet.ReduceDomain(hoImage, roi1, out HObject regionRoi);
                                            //HOperatorSet.Threshold(regionRoi, out AreaHobj1, 0, 110);
                                            //HOperatorSet.ClosingCircle(AreaHobj1, out AreaHobj1, 1);
                                            //HOperatorSet.Connection(AreaHobj1, out AreaHobj1);
                                            //HOperatorSet.FillUp(AreaHobj1, out AreaHobj1);
                                            //HOperatorSet.OpeningRectangle1(AreaHobj1, out AreaHobj1, 200, 1);
                                            //HOperatorSet.OpeningRectangle1(AreaHobj1, out AreaHobj1, 1, 101);
                                            //HOperatorSet.ClosingCircle(AreaHobj1, out AreaHobj1, 30);
                                            //HOperatorSet.OpeningCircle(AreaHobj1, out AreaHobj1, 30);
                                            //HOperatorSet.Connection(AreaHobj1, out AreaHobj1);
                                            //HOperatorSet.SelectShapeStd(AreaHobj1, out AreaHobj1, "max_area", 70);
                                            //HOperatorSet.ShapeTrans(AreaHobj1, out AreaHobj1,"convex");

                                            //////已经贴
                                            //HOperatorSet.GenRectangle2(out HObject rect, 615, 1324,0, 136, 106);
                                            //HOperatorSet.ReduceDomain(hoImage, rect, out HObject regEroR);
                                            //HOperatorSet.Threshold(regEroR, out HObject HobjEro, 0, 70);
                                            //HOperatorSet.Connection(HobjEro, out HobjEro);
                                            //HOperatorSet.SelectShape(HobjEro, out HobjEro, "area", "and",20000,99999999);
                                            //HOperatorSet.AreaCenter(HobjEro, out HTuple areakk, out _, out _);
                                            //HOperatorSet.CountObj(HobjEro, out HTuple num);
                                            //if (num.I > 0)
                                            //{
                                            //    isHavePos = true;
                                            //    GlobalVar.imageDisplay3_obj(rect, "blue");
                                            //    displalyInfo.displayInfoMain($"检测治具定位平台1 检测已经贴膜");
                                            //}
                                            ////其他区域
                                            //HOperatorSet.MoveRegion(AreaHobj1, out HObject moveReg, 1, 150);
                                            //HOperatorSet.ReduceDomain(hoImage, moveReg, out moveReg);
                                            //HOperatorSet.Threshold(moveReg, out HObject Hobj1, 0, 140);
                                            //HOperatorSet.ClosingRectangle1(Hobj1, out Hobj1, 3, 20);
                                            //HOperatorSet.ClosingRectangle1(Hobj1, out Hobj1, 20, 3);
                                            //HOperatorSet.OpeningCircle(Hobj1, out Hobj1, 15);
                                            //HOperatorSet.Connection(Hobj1, out Hobj1);
                                            //HOperatorSet.FillUp(Hobj1, out Hobj1);
                                            //HOperatorSet.SelectShapeStd(Hobj1, out Hobj1, "max_area", 70);
                                            //HOperatorSet.Union2(Hobj1, AreaHobj1, out AreaHobj1);
                                            //HOperatorSet.Union1(AreaHobj1, out AreaHobj1);

                                            //HOperatorSet.AreaCenter(AreaHobj1, out HTuple area1, out HTuple row_Cut1, out HTuple col_Cut1);
                                            //HOperatorSet.SmallestRectangle2(AreaHobj1, out HTuple row1, out HTuple col1, out HTuple phi1, out HTuple dH1, out HTuple dw1);
                                            ////
                                            //HOperatorSet.ReduceDomain(hoImage, roi2, out HObject regionRoi2);
                                            //HOperatorSet.Threshold(regionRoi2, out AreaHobj2, 0, 110);
                                            //HOperatorSet.ClosingCircle(AreaHobj2, out AreaHobj2, 1);
                                            //HOperatorSet.Connection(AreaHobj2, out AreaHobj2);
                                            //HOperatorSet.FillUp(AreaHobj2, out AreaHobj2);
                                            //HOperatorSet.OpeningRectangle1(AreaHobj2, out AreaHobj2, 201, 1);
                                            //HOperatorSet.OpeningRectangle1(AreaHobj2, out AreaHobj2, 1, 101);
                                            //HOperatorSet.ClosingCircle(AreaHobj2, out AreaHobj2, 30);
                                            //HOperatorSet.OpeningCircle(AreaHobj1, out AreaHobj1, 30);
                                            //HOperatorSet.Connection(AreaHobj2, out AreaHobj2);
                                            //HOperatorSet.SelectShapeStd(AreaHobj2, out AreaHobj2, "max_area", 70);
                                            //HOperatorSet.ShapeTrans(AreaHobj2, out AreaHobj2, "convex");
                                            ////下
                                            //HOperatorSet.MoveRegion(AreaHobj2, out HObject moveReg2, 1, 100);
                                            //HOperatorSet.ReduceDomain(hoImage, moveReg2, out moveReg2);
                                            //HOperatorSet.Threshold(moveReg2, out HObject Hobj2, 0, 140);
                                            //HOperatorSet.ClosingRectangle1(Hobj2, out Hobj2, 3, 20);
                                            //HOperatorSet.ClosingRectangle1(Hobj2, out Hobj2, 20, 3);
                                            //HOperatorSet.OpeningCircle(Hobj2, out Hobj2, 15);
                                            //HOperatorSet.Connection(Hobj2, out Hobj2);
                                            //HOperatorSet.FillUp(Hobj2, out Hobj2);
                                            //HOperatorSet.SelectShapeStd(Hobj2, out Hobj2, "max_area", 70);
                                            //HOperatorSet.Union2(Hobj2, AreaHobj2, out AreaHobj2);
                                            //HOperatorSet.Union1(AreaHobj2, out AreaHobj2);

                                            //HOperatorSet.AreaCenter(AreaHobj2, out HTuple area2, out HTuple row_Cut2, out HTuple col_Cut2);
                                            //HOperatorSet.SmallestRectangle2(AreaHobj2, out HTuple row2, out HTuple col2, out HTuple phi2, out HTuple dH2, out HTuple dw2);
                                            //var center1 = new VisionPos() { X = col_Cut1[0].D, Y = row_Cut1[0].D, R = dw1.D * 2 };
                                            //var center2 = new VisionPos() { X = col_Cut2[0].D, Y = row_Cut2[0].D, R = dw2.D * 2 };
                                            
                                            //原有模式
                                            var center1 = findCircleCheck(hoImage, GlobalVar.motionConfig.CircleFindCheck1[(int)e_Circle.找圆1], visionProc.ROI_M_List1[(int)e_RegionCheck.找圆区域1]);
                                            var center2 = findCircleCheck(hoImage, GlobalVar.motionConfig.CircleFindCheck1[(int)e_Circle.找圆2], visionProc.ROI_M_List1[(int)e_RegionCheck.找圆区域2]);

                                            if (center1!=null&& center2!=null)
                                            {
                                                displalyInfo.displayInfoMain($"平台1 圆心1X:{center1.X.ToString("F03")}Y:{center1.Y.ToString("F03")}圆心2X:{center2.X.ToString("F03")}Y:{center2.Y.ToString("F03")}");
                                                pos = CalcuteCenterPointAngle(new PointF(){X = (float)center1.X, Y = (float)center1.Y}, 
                                                    new PointF() {X = (float)center2.X, Y = (float)center2.Y});
                                            }
                                            else
                                            {
                                                pos = null;
                                                displalyInfo.displayErrorMain($"检测相机平台1 定位NG");
                                            }
                                        }

                                        //if (pos.X<900 || pos.X>1600)
                                        //{
                                        //    //偏差过大
                                        //    isHavePos = true;
                                        //    displalyInfo.displayInfoMain($"检测治具定位平台1 偏差过大");
                                        //}
                                        //else
                                        //{
                                        //    //if (!isHavePos)
                                        //    //{
                                        //    //    GlobalVar.imageDisplay3_obj(AreaHobj1, "blue");
                                        //    //    GlobalVar.imageDisplay3_obj(AreaHobj2, "blue");
                                        //    //}
                                        //}

                                        //1385
                                        if (pos != null && !isHavePos)
                                        {
                                            pos.R = 0;
                                            displalyInfo.displayErrorMain($"X:{pos.X.ToString("F04")}Y:{pos.Y.ToString("F04")}");
                                            var xPix = parama.RealX1 - pos.X;
                                            var yPix = parama.RealY1 - pos.Y;
                                            pos1pix = new AbsPostion() { R = pos.R, X = pos.X, Y = pos.Y };
                                            LabelPostion1 = new Postion()
                                            {
                                                X = xPix * parama.pixXReal,
                                                Y = yPix * parama.pixYReal,
                                                Angle = parama.RealR1 - pos.R,
                                            };

                                            HOperatorSet.GenCrossContourXld(out HObject crosing, pos.Y, pos.X, 100, pos.R);
                                            GlobalVar.imageDisplay3_obj(crosing, "red");
                                            displalyInfo.displayInfoMain($"平台1X:偏差{LabelPostion1.X.ToString("F04")}Y:偏差{LabelPostion1.Y.ToString("F04")}R:偏差{LabelPostion1.Angle.ToString("F04")}");
                                            GlobalVar.e_Camera_LabelPos1 = e_Camera_Pos.已拍照OK;
                                        }
                                        else
                                            GlobalVar.e_Camera_LabelPos1 = e_Camera_Pos.已拍照NG;
                                    }
                                    #endregion
                                }
                                else
                                    GlobalVar.e_Camera_LabelPos1 = e_Camera_Pos.已拍照NG;
                                return;
                            }
                            #endregion

                            #region 贴膜后
                            if (GlobalVar.motionConfig.vision_M1_list != null && GlobalVar.motionConfig.vision_M1_list.Count > 2)
                            {
                                displalyInfo.displayInfoMain($"检测贴标效果平台1");
                                #region 判断有无膜
                                HOperatorSet.ReduceDomain(visionProc.srcObject_ckeck, visionProc.ROI_M_List1[(int)e_RegionCheck.切图区域], out HObject cutObj);
                                HOperatorSet.Threshold(cutObj, out HObject threadObj, GlobalVar.motionConfig.cutParma1.GaryMin, GlobalVar.motionConfig.cutParma1.GaryMax);
                                HOperatorSet.Connection(threadObj, out threadObj);
                                HOperatorSet.FillUp(threadObj, out threadObj);
                                HOperatorSet.SelectShapeStd(threadObj, out threadObj, "max_area", 70);
                                //GetCutResult(visionProc.srcObject_ckeck, visionProc.ROI_M_List1[(int)e_RegionCheck.切图区域],
                                //         GlobalVar.motionConfig.cutParma1.GaryMin, GlobalVar.motionConfig.cutParma1.GaryMax, out HObject threadObj);
                                GlobalVar.imageDisplay3_obj(threadObj, "red");
                                HOperatorSet.GetRegionPoints(threadObj, out HTuple rs, out HTuple cs);
                                bool IsHave = rs.Length >= GlobalVar.motionConfig.cutParma1.AreaMin && rs.Length <= GlobalVar.motionConfig.cutParma1.AreaMax;
                                displalyInfo.displayInfoMain($"平台1有效面积为{rs.Length} 为" + (IsHave ? "*****有文字板*****" : "*****无文字板*****"));
                                #endregion

                                #region 判断有无贴偏
                                var msgstr = "";
                                var vParam1 = GlobalVar.motionConfig.vision_M1_list[(int)e_RegionCheck.检测区域1];
                                var vParam2 = GlobalVar.motionConfig.vision_M1_list[(int)e_RegionCheck.检测区域2];
                                var vParam3 = GlobalVar.motionConfig.vision_M1_list[(int)e_RegionCheck.检测区域3];
                                var vParam4 = GlobalVar.motionConfig.vision_M1_list[(int)e_RegionCheck.检测区域4];
                                var dis1 = visionProc.GetMeasures(e_CameraPlate.检测相机平台1, vParam1, e_RegionCheck.检测区域1);
                                var dis2 = visionProc.GetMeasures(e_CameraPlate.检测相机平台1, vParam2, e_RegionCheck.检测区域2);
                                var dis3 = visionProc.GetMeasures(e_CameraPlate.检测相机平台1, vParam3, e_RegionCheck.检测区域3);
                                var dis4 = visionProc.GetMeasures(e_CameraPlate.检测相机平台1, vParam4, e_RegionCheck.检测区域4);
                                msgstr += string.Join(",", dis1.ToArray());
                                if (dis1.Where(a => a >= vParam1.distanceMin && a <= vParam1.distanceMax).Count() == vParam1.nPar || (dis1.Count == 0 && vParam1.distanceMin == 0))
                                    msgstr += "      1OK";
                                else
                                    msgstr += "    1NG";
                                msgstr += string.Join(",", dis2.ToArray());
                                if (dis2.Where(a => a >= vParam2.distanceMin && a <= vParam2.distanceMax).Count() == vParam2.nPar || (dis2.Count == 0 && vParam2.distanceMin == 0))
                                    msgstr += "     2OK";
                                else
                                    msgstr += "     2NG";
                                msgstr += string.Join(",", dis3.ToArray());
                                if (dis3.Where(a => a >= vParam3.distanceMin && a <= vParam3.distanceMax).Count() == vParam3.nPar || (dis3.Count == 0 && vParam3.distanceMin == 0))
                                    msgstr += "     3OK";
                                else
                                    msgstr += "    3NG";
                                msgstr += string.Join(",", dis4.ToArray());
                                if (dis4.Where(a => a >= vParam4.distanceMin && a <= vParam4.distanceMax).Count() == vParam4.nPar || (dis4.Count == 0 && vParam4.distanceMin == 0))
                                    msgstr += "    4OK";
                                else
                                {

                                    msgstr += "    4NG";
                                }
                                displalyInfo.displayInfoMain($"平台1" + msgstr);
                                #endregion
                                GlobalVar.e_Camera_Check1 = (GlobalVar.userConfig.IsLabelResultOk || (IsHave && !msgstr.Contains("NG"))) ? e_Camera_Pos.已拍照OK : e_Camera_Pos.已拍照NG;
                            } else
                                GlobalVar.e_Camera_Check1 = e_Camera_Pos.已拍照NG;
                            #endregion
                        }
                        break;
                    case e_CameraPlate.检测相机平台2:
                        {
                            #region 贴膜前
                            if (GlobalVar.IsPosBeforeLabel)
                            {
                                displalyInfo.displayInfoMain($"检测治具定位平台2");
                                if (GlobalVar.motionConfig.posAfterLabel != null)
                                {

                                    var parama = GlobalVar.motionConfig.posAfterLabel;
                                    //  HOperatorSet.ReduceDomain(hoImage, visionProc.ROI_M_List2[(int)e_RegionCheck.预留], out HObject cutObj);
                                    #region 撕膜效果检测
                                    if (GlobalVar.userConfig.IsCheckCutResult)
                                    {
                                        HObject Reg1 = visionProc.ROI_M_List2[(int)e_RegionCheck.撕膜区域1];
                                        HObject Reg2 = visionProc.ROI_M_List2[(int)e_RegionCheck.撕膜区域2];
                                        HObject Reg3 = visionProc.ROI_M_List2[(int)e_RegionCheck.撕膜区域3];
                                        HOperatorSet.ReduceDomain(hoImage, Reg1, out HObject cutObj1);
                                        HOperatorSet.Threshold(cutObj1, out HObject region1, parama.grayMin2, parama.grayMax2);
                                        HOperatorSet.Connection(region1, out region1);
                                        HOperatorSet.FillUp(region1, out region1);
                                        HOperatorSet.SelectShapeStd(region1, out region1, "max_area", 70);
                                        HOperatorSet.AreaCenter(region1, out HTuple area1, out HTuple row_Cut1, out HTuple col_Cut1);
                                        HOperatorSet.ReduceDomain(hoImage, Reg2, out HObject cutObj2);
                                        HOperatorSet.Threshold(cutObj2, out HObject region2, parama.grayMin2, parama.grayMax2);
                                        HOperatorSet.Connection(region2, out region2);
                                        HOperatorSet.FillUp(region2, out region2);
                                        HOperatorSet.SelectShapeStd(region2, out region2, "max_area", 70);
                                        HOperatorSet.AreaCenter(region2, out HTuple area2, out HTuple row_Cut2, out HTuple col_Cut2);
                                        HOperatorSet.ReduceDomain(hoImage, Reg3, out HObject cutObj3);
                                        HOperatorSet.Threshold(cutObj3, out HObject region3, parama.grayMin2, parama.grayMax2);
                                        HOperatorSet.Connection(region3, out region3);
                                        HOperatorSet.FillUp(region3, out region3);
                                        HOperatorSet.SelectShapeStd(region3, out region3, "max_area", 70);
                                        HOperatorSet.AreaCenter(region3, out HTuple area3, out HTuple row_Cut3, out HTuple col_Cut3);
                                        if (area1.Type != HTupleType.EMPTY) AllArea += area1.D.ToString();
                                        if (area2.Type != HTupleType.EMPTY) AllArea += "," + area2.D.ToString();
                                        if (area3.Type != HTupleType.EMPTY) AllArea += "," + area3.D.ToString();
                                        if (area1.Type != HTupleType.EMPTY && area2.Type != HTupleType.EMPTY && area3.Type != HTupleType.EMPTY)
                                        {
                                            var areaLst = new List<double>();
                                            areaLst.Add(area1.D); areaLst.Add(area2.D); areaLst.Add(area3.D);
                                            if (areaLst.Where(a => a >= parama.areaMin2 && a <= parama.areaMax2).Count() > 0)

                                                GlobalVar.e_Camera_Cut2 = e_Camera_Pos.已拍照NG;
                                            else
                                                GlobalVar.e_Camera_Cut2 = e_Camera_Pos.已拍照OK;
                                            displalyInfo.displayInfoMain("撕膜面积:" + string.Join(",", areaLst));
                                            AllArea = string.Join(",", areaLst);

                                            GlobalVar.imageDisplay3_obj(region1, "red");
                                            GlobalVar.imageDisplay3_obj(region2, "red");
                                            GlobalVar.imageDisplay3_obj(region3, "red");
                                            GlobalVar.imageDisplay3_obj(Reg1, "green");
                                            GlobalVar.imageDisplay3_obj(Reg2, "green");
                                            GlobalVar.imageDisplay3_obj(Reg3, "green");
                                        }
                                        else
                                        {

                                            var str = "撕膜面积";
                                            if (area1.Type != HTupleType.EMPTY) str += "撕膜1面积" + area1.D.ToString();
                                            if (area2.Type != HTupleType.EMPTY) str += "撕膜2面积" + area2.D.ToString();
                                            if (area3.Type != HTupleType.EMPTY) str += "撕膜3面积" + area3.D.ToString();
                                            displalyInfo.displayInfoMain(str);
                                            GlobalVar.e_Camera_Cut2 = e_Camera_Pos.已拍照OK;
                                        }

                                       
                                      

                                        if (!GlobalVar.userConfig.IsPosAfterLabel)
                                            break;
                                    }
                                    #endregion

                                    if (GlobalVar.userConfig.IsPosAfterLabel)
                                    {
                                        var pos = new VisionPos();
                                        bool isHavePos = false;
                                        HObject AreaHobj1 = new HObject();
                                        HObject AreaHobj2 = new HObject();
                                        if (GlobalVar.motionConfig.IsEnableCircleCheck)
                                        {
                                            HObject roi1 = visionProc.ROI_M_List2[(int)e_RegionCheck.找圆区域1];
                                            HObject roi2 = visionProc.ROI_M_List2[(int)e_RegionCheck.找圆区域2];

                                            //HOperatorSet.ReduceDomain(hoImage, roi1, out HObject regionRoi);
                                            //HOperatorSet.Threshold(regionRoi, out AreaHobj1, 0, 100);
                                            //HOperatorSet.ClosingCircle(AreaHobj1, out AreaHobj1, 1);
                                            //HOperatorSet.Connection(AreaHobj1, out AreaHobj1);
                                            //HOperatorSet.FillUp(AreaHobj1, out AreaHobj1);
                                            //HOperatorSet.OpeningRectangle1(AreaHobj1, out AreaHobj1, 100, 1);
                                            //HOperatorSet.OpeningRectangle1(AreaHobj1, out AreaHobj1, 1, 101);
                                            //HOperatorSet.ClosingCircle(AreaHobj1, out AreaHobj1, 30);
                                            //HOperatorSet.OpeningCircle(AreaHobj1, out AreaHobj1, 30);
                                            //HOperatorSet.Connection(AreaHobj1, out AreaHobj1);
                                            //HOperatorSet.SelectShapeStd(AreaHobj1, out AreaHobj1, "max_area", 70);
                                            //HOperatorSet.ShapeTrans(AreaHobj1, out AreaHobj1, "convex");

                                            //////是否已经贴
                                            //HOperatorSet.GenRectangle2(out HObject rect, 680,4313, 0, 206, 106);
                                            //HOperatorSet.ReduceDomain(hoImage, rect, out HObject regEroR);
                                            //HOperatorSet.Threshold(regEroR, out HObject HobjEro, 0, 70);
                                            //HOperatorSet.Connection(HobjEro, out HobjEro);
                                            //HOperatorSet.SelectShape(HobjEro, out HobjEro, "area", "and", 20000, 99999999);
                                            //HOperatorSet.AreaCenter(HobjEro, out HTuple areakk, out _, out _);
                                            //HOperatorSet.CountObj(HobjEro, out HTuple num);
                                            //if (num.I > 0)
                                            //{
                                            //    GlobalVar.imageDisplay3_obj(rect, "blue");
                                            //    displalyInfo.displayInfoMain($"检测治具定位平台2 检测到已经贴膜");
                                            //    isHavePos = true;
                                            //}
                                            ////其他区域
                                            //HOperatorSet.MoveRegion(AreaHobj1, out HObject moveReg, 1, -150);
                                            //HOperatorSet.ReduceDomain(hoImage, moveReg, out moveReg);
                                            //HOperatorSet.Threshold(moveReg, out HObject Hobj1, 0, 140);
                                            //HOperatorSet.ClosingRectangle1(Hobj1, out Hobj1, 3, 20);
                                            //HOperatorSet.ClosingRectangle1(Hobj1, out Hobj1, 20, 3);
                                            //HOperatorSet.OpeningCircle(Hobj1, out Hobj1, 15);
                                            //HOperatorSet.Connection(Hobj1, out Hobj1);
                                            //HOperatorSet.FillUp(Hobj1, out Hobj1);
                                            //HOperatorSet.SelectShapeStd(Hobj1, out Hobj1, "max_area", 70);
                                            //HOperatorSet.Union2(Hobj1, AreaHobj1, out AreaHobj1);
                                            //HOperatorSet.Union1(AreaHobj1, out AreaHobj1);

                                            //HOperatorSet.AreaCenter(AreaHobj1, out HTuple area1, out HTuple row_Cut1, out HTuple col_Cut1);
                                            //HOperatorSet.SmallestRectangle2(AreaHobj1, out HTuple row1, out HTuple col1, out HTuple phi1, out HTuple dH1, out HTuple dw1);

                                            ////
                                            //HOperatorSet.ReduceDomain(hoImage, roi2, out HObject regionRoi2);
                                            //HOperatorSet.Threshold(regionRoi2, out AreaHobj2, 0, 100);
                                            //HOperatorSet.ClosingCircle(AreaHobj2, out AreaHobj2, 1);
                                            //HOperatorSet.Connection(AreaHobj2, out AreaHobj2);
                                            //HOperatorSet.FillUp(AreaHobj2, out AreaHobj2);
                                            //HOperatorSet.OpeningRectangle1(AreaHobj2, out AreaHobj2, 101, 1);
                                            //HOperatorSet.OpeningRectangle1(AreaHobj2, out AreaHobj2, 1, 101);
                                            //HOperatorSet.ClosingCircle(AreaHobj2, out AreaHobj2, 30);
                                            //HOperatorSet.OpeningCircle(AreaHobj1, out AreaHobj1, 30);
                                            //HOperatorSet.Connection(AreaHobj2, out AreaHobj2);
                                            //HOperatorSet.SelectShapeStd(AreaHobj2, out AreaHobj2, "max_area", 70);
                                            //HOperatorSet.ShapeTrans(AreaHobj2, out AreaHobj2, "convex");
                                            ////down
                                            //HOperatorSet.MoveRegion(AreaHobj2, out HObject moveReg2, 1, -100);
                                            //HOperatorSet.ReduceDomain(hoImage, moveReg2, out moveReg2);
                                            //HOperatorSet.Threshold(moveReg2, out HObject Hobj2, 0, 140);
                                            //HOperatorSet.ClosingRectangle1(Hobj2, out Hobj2, 3,20);
                                            //HOperatorSet.ClosingRectangle1(Hobj2, out Hobj2, 20, 3);
                                            //HOperatorSet.OpeningCircle(Hobj2, out Hobj2, 15);
                                            //HOperatorSet.Connection(Hobj2, out Hobj2);
                                            //HOperatorSet.FillUp(Hobj2, out Hobj2);
                                            //HOperatorSet.SelectShapeStd(Hobj2, out Hobj2, "max_area", 70);
                                            //HOperatorSet.Union2(Hobj2, AreaHobj2, out AreaHobj2);
                                            //HOperatorSet.Union1(AreaHobj2, out AreaHobj2);

                                            //HOperatorSet.AreaCenter(AreaHobj2, out HTuple area2, out HTuple row_Cut2, out HTuple col_Cut2);
                                            //HOperatorSet.SmallestRectangle2(AreaHobj2, out HTuple row2, out HTuple col2, out HTuple phi2, out HTuple dH2, out HTuple dw2);


                                            //var center1 = new VisionPos() { X = col_Cut1[0].D, Y = row_Cut1[0].D, R = dw1.D * 2 };
                                            //var center2 = new VisionPos() { X = col_Cut2[0].D, Y = row_Cut2[0].D, R = dw2.D * 2 };
                                            //原有模式
                                            var center1 = findCircleCheck(hoImage, GlobalVar.motionConfig.CircleFindCheck2[(int)e_Circle.找圆1], visionProc.ROI_M_List2[(int)e_RegionCheck.找圆区域1]);
                                            var center2 = findCircleCheck(hoImage, GlobalVar.motionConfig.CircleFindCheck2[(int)e_Circle.找圆2], visionProc.ROI_M_List2[(int)e_RegionCheck.找圆区域2]);

                                            if (center1 != null && center2 != null)
                                            {
                                                displalyInfo.displayInfoMain($"平台2 圆心1X:{center1.X.ToString("F03")}Y:{center1.Y.ToString("F03")}圆心2X:{center2.X.ToString("F03")}Y:{center2.Y.ToString("F03")}");
                                                pos = CalcuteCenterPointAngle(new PointF() { X = (float)center1.X, Y = (float)center1.Y },
                                                    new PointF() { X = (float)center2.X, Y = (float)center2.Y });
                                            }
                                            else
                                            {
                                                pos = null;
                                                displalyInfo.displayErrorMain($"检测相机平台2 定位NG");
                                            }
                                        }

                                        //if (pos.X < 3900 || pos.X > 4600)
                                        //{
                                        //    //偏差过大
                                        //    isHavePos = true;
                                        //    displalyInfo.displayInfoMain($"检测治具定位平台2 偏差过大");
                                        //}
                                        //else
                                        //{
                                        //    //if (!isHavePos)
                                        //    //{
                                        //    //    GlobalVar.imageDisplay3_obj(AreaHobj1, "blue");
                                        //    //    GlobalVar.imageDisplay3_obj(AreaHobj2, "blue");
                                        //    //}
                                        //}
                                        //4330
                                        if (pos != null && !isHavePos)
                                        {
                                            pos.R = 0;
                                            displalyInfo.displayErrorMain($"X:{pos.X.ToString("F04")}Y:{pos.Y.ToString("F04")}");
                                            var xPix = parama.RealX2 - pos.X;
                                            var yPix = parama.RealY2 - pos.Y;
                                            pos2pix = new AbsPostion() { R = pos.R, X = pos.X, Y = pos.Y };
                                            LabelPostion2 = new Postion()
                                            {
                                                X = xPix * parama.pixXReal,
                                                Y = yPix * parama.pixYReal,

                                                Angle = parama.RealR2 - pos.R,
                                            };
                                            HOperatorSet.GenCrossContourXld(out HObject crosing, pos.Y, pos.X, 100, pos.R);
                                            GlobalVar.imageDisplay3_obj(crosing, "red");
                                            displalyInfo.displayInfoMain($"平台2X:偏差{LabelPostion2.X.ToString("F04")}Y:偏差{LabelPostion2.Y.ToString("F04")}R:偏差{LabelPostion2.Angle.ToString("F04")}");
                                            GlobalVar.e_Camera_LabelPos2 = e_Camera_Pos.已拍照OK;
                                        }
                                        else
                                            GlobalVar.e_Camera_LabelPos2 = e_Camera_Pos.已拍照NG;
                                    }
                                }
                                else
                                {
                                    GlobalVar.e_Camera_LabelPos2 = e_Camera_Pos.已拍照NG;
                                }
                                return;
                            }
                            #endregion

                            #region 贴膜后
                            if (GlobalVar.motionConfig.vision_M2_list != null && GlobalVar.motionConfig.vision_M2_list.Count > 2)
                            {
                                displalyInfo.displayInfoMain($"检测治具平台2贴标效果");
                                #region 判断有无膜
                                HOperatorSet.ReduceDomain(visionProc.srcObject_ckeck, visionProc.ROI_M_List2[(int)e_RegionCheck.切图区域], out HObject cutObj);
                                HOperatorSet.Threshold(cutObj, out HObject threadObj, GlobalVar.motionConfig.cutParma2.GaryMin, GlobalVar.motionConfig.cutParma2.GaryMax);
                                //GetCutResult(visionProc.srcObject_ckeck, visionProc.ROI_M_List2[(int)e_RegionCheck.切图区域],
                                //         GlobalVar.motionConfig.cutParma2.GaryMin, GlobalVar.motionConfig.cutParma2.GaryMax, out HObject threadObj);
                                GlobalVar.imageDisplay3_obj(threadObj, "red");
                                HOperatorSet.GetRegionPoints(threadObj, out HTuple rs, out HTuple cs);
                                bool IsHave = rs.Length >= GlobalVar.motionConfig.cutParma2.AreaMin && rs.Length <= GlobalVar.motionConfig.cutParma2.AreaMax;
                                displalyInfo.displayInfoMain($"平台2 有效面积为{rs.Length} 为" + (IsHave ? "*****有文字板*****" : "*****无文字板*****"));
                                #endregion

                                #region 判断有无贴偏
                                var msgstr = "";
                                var vParam1 = GlobalVar.motionConfig.vision_M2_list[(int)e_RegionCheck.检测区域1];
                                var vParam2 = GlobalVar.motionConfig.vision_M2_list[(int)e_RegionCheck.检测区域2];
                                var vParam3 = GlobalVar.motionConfig.vision_M2_list[(int)e_RegionCheck.检测区域3];
                                var vParam4 = GlobalVar.motionConfig.vision_M2_list[(int)e_RegionCheck.检测区域4];
                                var dis1 = visionProc.GetMeasures(e_CameraPlate.检测相机平台2, vParam1, e_RegionCheck.检测区域1);
                                var dis2 = visionProc.GetMeasures(e_CameraPlate.检测相机平台2, vParam2, e_RegionCheck.检测区域2);
                                var dis3 = visionProc.GetMeasures(e_CameraPlate.检测相机平台2, vParam3, e_RegionCheck.检测区域3);
                                var dis4 = visionProc.GetMeasures(e_CameraPlate.检测相机平台2, vParam4, e_RegionCheck.检测区域4);
                                msgstr += string.Join(",", dis1.ToArray());
                                if (dis1.Where(a => a >= vParam1.distanceMin && a <= vParam1.distanceMax).Count() == vParam1.nPar || (dis1.Count == 0 && vParam1.distanceMin == 0))
                                    msgstr += "    1OK";
                                else
                                    msgstr += "    1NG";
                                msgstr += string.Join(",", dis2.ToArray());
                                if (dis2.Where(a => a >= vParam2.distanceMin && a <= vParam2.distanceMax).Count() == vParam2.nPar || (dis2.Count == 0 && vParam2.distanceMin == 0))
                                    msgstr += "     2OK";
                                else
                                    msgstr += "     2NG";
                                msgstr += string.Join(",", dis3.ToArray());
                                if (dis3.Where(a => a >= vParam3.distanceMin && a <= vParam3.distanceMax).Count() == vParam3.nPar || (dis3.Count == 0 && vParam3.distanceMin == 0))
                                    msgstr += "     3OK";
                                else
                                    msgstr += "    3NG";
                                msgstr += string.Join(",", dis4.ToArray());
                                if (dis4.Where(a => a >= vParam4.distanceMin && a <= vParam4.distanceMax).Count() == vParam4.nPar || (dis4.Count == 0 && vParam4.distanceMin == 0))
                                    msgstr += "    4OK";
                                else
                                {
                                    msgstr += "    4NG";
                                }
                                displalyInfo.displayInfoMain($"平台2" + msgstr);
                                #endregion
                                GlobalVar.e_Camera_Check2 = (GlobalVar.userConfig.IsLabelResultOk || (IsHave && !msgstr.Contains("NG"))) ? e_Camera_Pos.已拍照OK : e_Camera_Pos.已拍照NG;
                            }
                            else
                                GlobalVar.e_Camera_Check2 = e_Camera_Pos.已拍照NG;
                            #endregion
                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                GlobalVar.e_Camera_Cut1 = e_Camera_Pos.已拍照NG;
                GlobalVar.e_Camera_Cut2 = e_Camera_Pos.已拍照NG;
                GlobalVar.e_Camera_LabelPos1 = e_Camera_Pos.已拍照NG;
                GlobalVar.e_Camera_LabelPos2 = e_Camera_Pos.已拍照NG;
                GlobalVar.e_Camera_Check1 = e_Camera_Pos.已拍照NG;
                GlobalVar.e_Camera_Check2 = e_Camera_Pos.已拍照NG;
                GlobalVar.e_Camera_Pos1 = e_Camera_Pos.已拍照NG;
                GlobalVar.e_Camera_Pos2 = e_Camera_Pos.已拍照NG;
                GlobalVar.e_Camera_Word1 = e_Camera_Pos.已拍照NG;
                GlobalVar.e_Camera_Word2 = e_Camera_Pos.已拍照NG;
                Log4Helper.WriteLog(ex);
            }
        }

        public static HObject GetCutResult( HObject img,HObject regROI, HTuple grayMin2,HTuple grayMax2, out HObject obj)
        {
            obj = new HObject();
            HOperatorSet.ReduceDomain(img, regROI, out HObject cutObj1);
            HOperatorSet.Threshold(cutObj1, out HObject region1, grayMin2, grayMax2);
            HOperatorSet.ClosingCircle(region1, out region1, 3);
            HOperatorSet.OpeningCircle(region1, out region1, 3);
            HOperatorSet.Connection(region1, out region1);
            HOperatorSet.FillUp(region1, out region1);
            HOperatorSet.SelectShapeStd(region1, out obj, "max_area", 70);

            return obj;
        }

        public static Postion CPos;
        public static Postion TransPoint(Postion result, PlateVisionInfo cailInfo, AbsPostion scanPos, AbsPostion putPos, VisionPos pos)
        {
            var res = new Postion();

            ///放料位-拍照位
            var vPos = new AbsPostion() { X = putPos.X - scanPos.X, Y = putPos.Y - scanPos.Y, R = putPos.R - scanPos.R };

            //旋转90度
            HOperatorSet.HomMat2dIdentity(out HTuple hv_HomMat2DRotate1);
            var Angle = vPos.R * 55 / 20000 * 360;
            var rad1 = Angle / 180 * Math.PI;
            HOperatorSet.HomMat2dRotate(hv_HomMat2DRotate1, rad1, cailInfo.rorateOffsetX + scanPos.X, cailInfo.rorateOffsetY + scanPos.Y, out HTuple hv_HomMat2D);
            HOperatorSet.AffineTransPoint2d(hv_HomMat2D, result.X, result.Y, out HTuple RealX2, out HTuple RealY2);

            int N = 0;
            ///打印当前补偿值
            var varTempX = putPos.X - RealX2.D;///                          与标准放料位的相对位置X
            var varTempY = putPos.Y - RealY2.D;///在拍照位那边旋转90度      与标准放料位的相对位置Y
            displalyInfo.displayInfoMain($"到放标位的相对位置补偿X:{varTempX}补偿Y:{varTempY}");
            CPos = new Postion() { X = varTempX, Y = varTempY, Angle = result.Angle };
            ///放回放标位
            var xVar = RealX2.D + pos.X - putPos.X;//X放标位需要补偿的
            var yVar = RealY2.D + pos.Y - putPos.Y;//X放标位需要补偿的

            return new Postion() { X = xVar, Y = yVar, Angle = result.Angle + pos.R };
        }

        public static void RotateAngle(double XRotation, double YRotation, double ARotate, double XBefore, double YBefore, ref double XAfter, ref double YAfter)
        {

            try
            {

                double Rad = 0;
                Rad = ARotate * Math.Acos(-1) / 180;
                XAfter = (XBefore - XRotation) * Math.Cos(Rad) - (YBefore - YRotation) * Math.Sin(Rad) + XRotation;
                YAfter = (YBefore - YRotation) * Math.Cos(Rad) + (XBefore - XRotation) * Math.Sin(Rad) + YRotation;
                //XAfter=(XBefore - XRotation) / Math.Cos(ARotate) + (XBefore - XRotation) / Math.Cos(ARotate) * Math.Sin(ARotate) + XRotation;
                //YAfter = (YBefore - YRotation) / Math.Sin(ARotate) + (YBefore - YRotation) / Math.Sin(ARotate) * Math.Sin(ARotate) + YRotation;


            }
            catch (Exception ex)
            {


            }
        }
        /// <summary>
        /// 计算与基准点的半径+角度关系
        /// </summary>
        /// <param name="lockobJ"></param>
        /// <param name="nextPoint"></param>
        /// <returns>第0个参数为半径  第二参数为角度</returns>
     public static List<double>CaculateRangle(PointF basePoint, PointF nextPoint)
        {
            var res = new List<double>();
            try
            {
                var x = nextPoint.X - basePoint.X;
                var y = basePoint.Y - nextPoint.Y;
                var Radius = Math.Sqrt(x * x + y * y);
                var Angle = Math.Atan2(y, x);
                if (Angle == System.Double.NaN)
                {
                    if (x == y)
                        Angle = Math.PI / 2;
                    else
                        Angle = -Math.PI / 2;
                }
                res.Add(Radius);

                res.Add(Angle / Math.PI * 180);
                return res;
            }
            catch (Exception ex)
            {
                return res;
            }
        }
       /// <summary>
       /// 基准点的R+角度方向的点坐标
       /// </summary>
       /// <param name="basePoint"></param>
       /// <param name="Angel"></param>
       /// <param name="R"></param>
       /// <returns></returns>
        public static List<double> CaculateNextPoint(PointF basePoint, double Angel,double R)
        {
            var res = new List<double>();
            try
            {
                if (Angel > 360)
                    Angel -= 360- Angel;
                var varX = R * Math.Cos(Angel/180* Math.PI);
                var varY = R * Math.Sin(Angel / 180* Math.PI);
                double X =(double) basePoint.X+ varX;
                double Y = (double)basePoint.Y-varY;
                res.Add(X);
                res.Add(Y);
                return res;
            }
            catch (Exception ex)
            {
                return res;
            }
        }

        #region H230264
        public static HObject DrawCrossing(double row, double col, double angle)
        {

            HOperatorSet.GenCrossContourXld(out HObject cross, row, col, 200, angle);
            return cross;

        }
        /// <summary>
        /// 计算标定矩阵
        /// </summary>
        /// <param name="camera"></param>
        /// <returns></returns>
        public static HTuple Calibrate(e_CameraPlate camera)
        {
            HTuple hv_HomMat2D;
            HOperatorSet.VectorToHomMat2d(GlobalVar.hv_calibrate_pix_x, GlobalVar.hv_calibrate_pix_y, GlobalVar.hv_calibrate_real_x, GlobalVar.hv_calibrate_real_y, out hv_HomMat2D);
            displalyInfo.displayInfoMain($"标定数据：{hv_HomMat2D}");
            HOperatorSet.SerializeHomMat2d(hv_HomMat2D, out HTuple hv_SerializedItemHandle);
            HOperatorSet.OpenFile(GlobalVar.calibrationPath + $"\\calib{(int)camera}.cal", "output_binary", out HTuple hv_FileHandle);
            HOperatorSet.FwriteSerializedItem(hv_FileHandle, hv_SerializedItemHandle);
            HOperatorSet.CloseFile(hv_FileHandle);
            displalyInfo.displayInfoMain($"{camera.ToString()}标定文件已保存");
            return hv_HomMat2D;
        }
        public static HTuple CalibratePlate(List<PointF> pix, List<PointF> real)
        {
            HTuple hv_HomMat2D;
            var xArr = new List<double>();
            var yArr = new List<double>();
            for (int i = 0; i < pix.Count; i++)
            {
                xArr.Add(Convert.ToDouble(pix[i].X));
                yArr.Add(Convert.ToDouble(pix[i].Y));
            }
            var xArrReal = new List<double>();
            var yArrReal = new List<double>();
            for (int i = 0; i < real.Count; i++)
            {
                xArrReal.Add(Convert.ToDouble(real[i].X));
                yArrReal.Add(Convert.ToDouble(real[i].Y));
            }
            HOperatorSet.VectorToHomMat2d(xArr.ToArray(), yArr.ToArray(), xArrReal.ToArray(), yArrReal.ToArray(), out hv_HomMat2D);

            return hv_HomMat2D;
        }
        /// <summary>
        /// 先计算标定矩阵  再执行计算
        /// </summary>
        /// <param name="arr_cail"></param>
        /// <param name="camera"></param>
        /// <returns></returns>
        public static PointF CalibrateRotateCenter(double[] arr_cail, List<PointF> pixPoint, PointF actPoint)
        {

            try
            {
                RorateOffset = new PointF() { X = -1, Y = -1 };
                var xArr = new List<double>();
                var yArr = new List<double>();
                for (int i = 0; i < pixPoint.Count; i++)
                {
                    xArr.Add(Convert.ToDouble(pixPoint[i].X));
                    yArr.Add(Convert.ToDouble(pixPoint[i].Y));
                }
                //像素旋转中心转化为实际旋转中心
                var Realpoint = new PointF() { X = 0.0f, Y = 0.0f };


                //var PointPix = new PointF() { X = 0.0f, Y = 0.0f };
                HObject circle = new HObject();
                HOperatorSet.GenContourPolygonXld(out circle, yArr.ToArray(), xArr.ToArray());
                HOperatorSet.FitCircleContourXld(circle, "geotukey", -1, 0, 0, 3, 2, out HTuple row, out HTuple col, out HTuple radius, out HTuple startPhi, out HTuple endPhi, out HTuple pointOrder);
                //   HOperatorSet.FitCircleContourXld(circle, "algebraic", -1, 0, 0, 3, 2, out HTuple row, out HTuple col, out HTuple radius, out HTuple startPhi, out HTuple endPhi, out HTuple pointOrder);
                //PointPix.X = (float)col.D;
                //PointPix.Y = (float)row.D;
                HOperatorSet.GenCrossContourXld(out HObject crosing, row, col, 200, 0);
                GlobalVar.imageDisplay1_obj(crosing, "black");
                RoratePix = new PointF() { Y = (float)row.D, X = (float)col.D };
                HOperatorSet.AffineTransPoint2d(arr_cail, col, row, out HTuple real_x, out HTuple real_y);
                Realpoint.X = (float)real_x.D;
                Realpoint.Y = (float)real_y.D;

                #region 新
                var xArrAct = new List<double>();
                var yArrAct = new List<double>();
                for (int i = 0; i < xArr.Count; i++)
                {
                    HOperatorSet.AffineTransPoint2d(arr_cail, xArr[i], yArr[i], out HTuple tempX, out HTuple tempY);
                    xArrAct.Add(tempX.D);
                    yArrAct.Add(tempY.D);
                }
                HOperatorSet.AffineTransPoint2d(arr_cail, RoratePix.X, RoratePix.Y, out HTuple realX, out HTuple realY);
                HOperatorSet.GenContourPolygonXld(out HObject circle2, xArrAct.ToArray(), yArrAct.ToArray());
                HOperatorSet.FitCircleContourXld(circle2, "geotukey", -1, 0, 0, 3, 2, out HTuple row2, out HTuple col2, out HTuple radius2, out HTuple startPhi2, out HTuple endPhi2, out HTuple pointOrder2);
                var realpoint2 = new PointF() { X = (float)realX.D, Y = (float)realY.D };
                displalyInfo.displayInfoMain($"新实际旋转中心X：{realpoint2.X} Y：{realpoint2.Y}");
                RorateOffset = new PointF() { X = realpoint2.X - actPoint.X, Y = realpoint2.Y - actPoint.Y };
                displalyInfo.displayInfoMain($"减去当前机器坐标旋转中心X：{RorateOffset.X} Y：{RorateOffset.Y}");
                #endregion
                displalyInfo.displayInfoMain($"像素旋转中心X：{RoratePix.X} Y：{RoratePix.Y}");
                //displalyInfo.displayInfoMain($"实际旋转中心X：{RoratePix.X} Y：{RoratePix.Y}");
                return RoratePix;
            }
            catch (Exception ex)
            {
                return new PointF() { X = -1000000f, Y = -100000f };
            }
        }
        public static PointF RoratePix = new PointF();
        public static HObject Crossing_CenterPix1;
        public static HObject Crossing_CenterPix2;
        /// <summary>
        /// 根据传进来的像素坐标+角度     九点标定+机械旋转中心   计算出在范围内的结果
        /// </summary>
        /// <param name="curPix"></param>
        /// <param name="arr_cail"></param>
        /// <param name="RotateCenterPoint"></param>
        /// <returns></returns>
        public static Postion CalibratePostion(Postion curPix, PlateVisionInfo cailInfo, PointF scanPos, VisionPos centerPos, VisionPos basePos)
        {
            var pos = new Postion();
            try
            {
                var rotatePixX = cailInfo.CenterRealX;
                var rotatePixY = cailInfo.CenterRealY;
                ///折算出当前拍照位的旋转中心像素坐标
                //HOperatorSet.AffineTransPoint2d(cailInfo.arr_cail, cailInfo.CenterRealX, cailInfo.CenterRealY, out HTuple rotateRealX, out HTuple rotateRealY);
                //var xVar = scanPos.X - cailInfo.CailPointX;
                //var yVar = scanPos.Y - cailInfo.CailPointY;
                //HOperatorSet.AffineTransPoint2d(cailInfo.arr_pixcail, rotateRealX + xVar, rotateRealY + yVar, out HTuple rotateRealX2, out HTuple rotateRealY2);

                //          HOperatorSet.AffineTransPoint2d(cailInfo.arr_pixcail, rotateRealX + xVar, rotateRealY + yVar, out HTuple rotateRealX2, out HTuple rotateRealY2);
                //rotatePixX = rotateRealX2.D;
                //rotatePixY = rotateRealY2.D;
                ///
                HOperatorSet.AffineTransPoint2d(cailInfo.arr_pixcail, cailInfo.rorateOffsetX + scanPos.X, cailInfo.rorateOffsetY + scanPos.Y, out HTuple rotateRealX2, out HTuple rotateRealY2);
                rotatePixX = rotateRealX2.D;
                rotatePixY = rotateRealY2.D;
                HOperatorSet.HomMat2dIdentity(out HTuple hv_HomMat2DRotate90);

                var rad = curPix.Angle / 180 * Math.PI;
                pos.Angle = curPix.Angle;
                if (curPix.Angle > 180)
                {
                    rad = (curPix.Angle - 360) / 180 * Math.PI;
                    pos.Angle = curPix.Angle - 360;
                }
                HOperatorSet.HomMat2dRotate(hv_HomMat2DRotate90, rad, rotatePixX, rotatePixY, out HTuple hv_HomMat2DNewPix);
                HOperatorSet.AffineTransPoint2d(hv_HomMat2DNewPix, curPix.X, curPix.Y, out HTuple pixX, out HTuple pixY);
                Mark1Pix = new PointF() { X = (float)pixX.D, Y = (float)pixY.D };
                HOperatorSet.GenCrossContourXld(out HObject Mark, pixY, pixX, 200, 0);
                var CenterPix = new PointF() { X = Mark1Pix.X + (float)centerPos.X, Y = (float)Mark1Pix.Y + (float)centerPos.Y };
                HOperatorSet.GenCrossContourXld(out Crossing_CenterPix1, CenterPix.Y, CenterPix.X, 200, 0);
                HOperatorSet.AffineTransPoint2d(cailInfo.arr_cail, CenterPix.X, CenterPix.Y, out HTuple actX1, out HTuple actY1);
                displalyInfo.displayInfoMain($"产品中心像素X:{CenterPix.X.ToString("F03")}y:{CenterPix.Y.ToString("F03")}");
                GlobalVar.imageDisplay1_obj(Mark, "green");
                GlobalVar.imageDisplay1_obj(Crossing_CenterPix1, "blue");

                BasePostion1 = new Postion() { X = actX1.D, Y = actY1.D };
                var newX = basePos.X-actX1.D ;
                var newY = basePos.Y -actY1.D;
                pos.X = (double)basePos.X - newX;
                pos.Y = (double)basePos.Y - newY;
                pos.X = actX1.D;
                pos.Y =actY1.D;
                return pos;

            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public static Postion CalibratePostion2(Postion curPix, PlateVisionInfo cailInfo, PointF scanPos, VisionPos centerPos, VisionPos basePos )
        {
            var pos = new Postion();
            try
            {
                var rotatePixX = cailInfo.CenterRealX;
                var rotatePixY = cailInfo.CenterRealY;
                ///折算出当前拍照位的旋转中心像素坐标
                HOperatorSet.AffineTransPoint2d(cailInfo.arr_cail, cailInfo.CenterRealX, cailInfo.CenterRealY, out HTuple rotateRealX, out HTuple rotateRealY);
                var xVar = scanPos.X - cailInfo.CailPointX;
                var yVar = scanPos.Y - cailInfo.CailPointY;
                HOperatorSet.AffineTransPoint2d(cailInfo.arr_pixcail, rotateRealX + xVar, rotateRealY + yVar, out HTuple rotateRealX2, out HTuple rotateRealY2);

            
                rotatePixX = rotateRealX2.D;
                rotatePixY = rotateRealY2.D;
                ///

                HOperatorSet.HomMat2dIdentity(out HTuple hv_HomMat2DRotate90);

                var rad = curPix.Angle / 180 * Math.PI;
                pos.Angle = curPix.Angle;
                if (curPix.Angle > 180)
                {
                    rad = (curPix.Angle - 360) / 180 * Math.PI;
                    pos.Angle = curPix.Angle - 360;
                }
                HOperatorSet.HomMat2dRotate(hv_HomMat2DRotate90, rad, rotatePixX, rotatePixY, out HTuple hv_HomMat2DNewPix);
                HOperatorSet.AffineTransPoint2d(hv_HomMat2DNewPix, curPix.X, curPix.Y, out HTuple pixX, out HTuple pixY);
                Mark2Pix = new PointF() { X = (float)pixX.D, Y = (float)pixY.D };
                HOperatorSet.GenCrossContourXld(out HObject Mark, pixY, pixX, 200, 0);
                var CenterPix = new PointF() { X = Mark2Pix.X + (float)centerPos.X, Y = (float)Mark2Pix.Y + (float)centerPos.Y };
                HOperatorSet.GenCrossContourXld(out Crossing_CenterPix2, CenterPix.Y, CenterPix.X, 200, 0);
                HOperatorSet.AffineTransPoint2d(cailInfo.arr_cail, CenterPix.X, CenterPix.Y, out HTuple actX1, out HTuple actY1);
                displalyInfo.displayInfoMain($"产品中心像素X:{CenterPix.X.ToString("F03")}y:{CenterPix.Y.ToString("F03")}");
                GlobalVar.imageDisplay1_obj(Mark, "green");
                GlobalVar.imageDisplay1_obj(Crossing_CenterPix2, "blue");
                BasePostion2 = new Postion() { X = actX1.D, Y = actY1.D };
                var newX = basePos.X - actX1.D;
                var newY = basePos.Y - actY1.D;
                pos.X = (double)basePos.X - newX;
                pos.Y = (double)basePos.Y - newY;
                pos.X = (double)actX1.D;
                pos.Y = (double)actY1.D;
                return pos;

            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public static PointF Mark1Pix = new PointF();
        public static PointF Mark2Pix = new PointF();
        public static Postion CalibratePostion2(Postion curPix, HTuple arr_cail, PointF RotateCenterPoint)
        {
            var pos = new Postion();
            try
            {
                // HOperatorSet.AffineTransPixel(arr_cail, curPix.X, curPix.Y, out HTuple real_x, out HTuple real_y);
                //HOperatorSet.HomMat2dIdentity(out HTuple hv_HomMat2DRotate90);

                //HOperatorSet.HomMat2dRotate(hv_HomMat2DRotate90, curPix.Angle / 180 * Math.PI, RotateCenterPoint.X, RotateCenterPoint.Y, out HTuple hv_HomMat2DNew);
                HOperatorSet.AffineTransPoint2d(arr_cail, curPix.X, curPix.Y, out HTuple actX, out HTuple actY);
                pos.X = (double)actX.D;
                pos.Y = (double)actY.D;
                if (pos.X > curPix.xMax || pos.X < curPix.xMin || pos.Y > curPix.yMax || pos.Y < curPix.yMin)
                    return null;
                else
                    return pos;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public static List<HObject> CheckROI1;
        public static List<HObject> CheckROI2;
        public static List<double> GetMeasures(e_CameraPlate cameraPlate, MeasureParma measureParma, e_RegionCheck m_check)
        {
            var res = new List<double>();
            var curHobject = new HObject();
            switch (cameraPlate)
            {
                case e_CameraPlate.检测相机平台1:
                    curHobject = ROI_M_List1[(int)m_check];
                    break;
                case e_CameraPlate.检测相机平台2:
                    curHobject = ROI_M_List2[(int)m_check];
                    break;
            }
            HOperatorSet.GetImageSize(srcObject_ckeck, out HTuple width, out HTuple height);
            //
            try
            {
                HOperatorSet.SmallestRectangle2(curHobject, out HTuple row1, out HTuple col1, out HTuple phi1, out HTuple rLength, out HTuple cLength);
                HOperatorSet.GenRectangle2(out HObject temp, row1, col1, phi1, rLength, 1);
                GlobalVar.imageDisplay3_obj(temp, "red");
                HOperatorSet.GenMeasureRectangle2(row1, col1, phi1, rLength, cLength, width, height, measureParma.Interpolation, out HTuple HandleMeasure1);
                HOperatorSet.MeasurePos(srcObject_ckeck, HandleMeasure1, measureParma.dSigma, measureParma.dThreshold, measureParma.Transition, measureParma.Select,
                out HTuple rowEdge, out HTuple columnEdge, out HTuple amplitude, out HTuple Distance);
                HOperatorSet.CloseMeasure(HandleMeasure1);
                if (rowEdge.Type != HTupleType.EMPTY)
                {
                    if (rowEdge.DArr.Length > 1)
                    {
                        var nMax = rowEdge.DArr.Length;
                        HOperatorSet.DistancePp(rowEdge.DArr[0], columnEdge.DArr[0], rowEdge.DArr[nMax - 1], columnEdge.DArr[nMax - 1], out HTuple distance);
                        for (int i = 0; i < rowEdge.DArr.Length; i++)
                        {
                            if (i == 0 || i == (nMax - 1))
                            {
                                var dr1 = rowEdge.DArr[i];
                                var dc1 = columnEdge.DArr[i];
                                HOperatorSet.GenCrossContourXld(out HObject crossing, dr1, dc1, 10, 0);
                                GlobalVar.imageDisplay3_obj(crossing, "green");
                            }
                        }
                        return distance.DArr.ToList();
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return res;
        }
        #endregion
        #region 绘制ROI

        private static List<HDrawingObject> draw_up_region_template1 = new List<HDrawingObject>();
        private static List<HDrawingObject> draw_up_region_template2 = new List<HDrawingObject>();
        private static List<HDrawingObject> draw_up_region_template3 = new List<HDrawingObject>();
        public static void ClearROIRegion1()
        {

            foreach (HDrawingObject dobj in visionProc.draw_up_region_template1)
                dobj.Dispose();
            draw_up_region_template1.Clear();
            MarkRegion = null;

        }
        public static void ClearROIRegion3()
        {

            foreach (HDrawingObject dobj in visionProc.draw_up_region_template3)
                dobj.Dispose();
            draw_up_region_template3.Clear();


        }
        public static void ClearROIRegion2()
        {

            foreach (HDrawingObject dobj in visionProc.draw_up_region_template2)
                dobj.Dispose();
            draw_up_region_template2.Clear();


        }
        public static void DrawRoiRegion1(HSmartWindowControl hSmartWindow)
        {
            if (draw_up_region_template1 == null)
            {
                draw_up_region_template1 = new List<HDrawingObject>();
            }
            if (draw_up_region_template1.Count > 0)
                return;
            HDrawingObject rect2 = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2, 300, 300, 0, 100, 50);
            rect2.SetDrawingObjectParams("color", "blue");
            AttachDrawObj(rect2, hSmartWindow.HalconWindow, draw_up_region_template1);
        }
        public static void DrawRoiRegion3(HSmartWindowControl hSmartWindow)
        {
            if (draw_up_region_template3 == null)
            {
                draw_up_region_template3 = new List<HDrawingObject>();
            }
            if (draw_up_region_template3.Count > 0)
                return;
            HDrawingObject rect2 = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2, 300, 300, 0, 100, 50);
            rect2.SetDrawingObjectParams("color", "blue");
            AttachDrawObj(rect2, hSmartWindow.HalconWindow, draw_up_region_template3);
        }
        public static void DrawRoiRegion2(HSmartWindowControl hSmartWindow)
        {
            if (draw_up_region_template2 == null)
            {
                draw_up_region_template2 = new List<HDrawingObject>();
            }
            if (draw_up_region_template2.Count > 0)
                return;
            HDrawingObject rect2 = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2, 300, 300, 0, 100, 50);
            rect2.SetDrawingObjectParams("color", "blue");
            AttachDrawObj(rect2, hSmartWindow.HalconWindow, draw_up_region_template2);
        }
        private static void AttachDrawObj(HDrawingObject obj, HWindow hwin, List<HDrawingObject> drawing_objects)
        {
            drawing_objects.Add(obj);
            // The HALCON/C# interface offers convenience methods that
            // encapsulate the set_drawing_object_callback operator.
            obj.OnDrag(roi_save);
            obj.OnAttach(roi_save);
            obj.OnResize(roi_save);
            obj.OnSelect(roi_save);
            obj.OnAttach(roi_save);
            if (selected_drawing_object == null)
                selected_drawing_object = obj;
            hwin.AttachDrawingObjectToWindow(obj);
        }
        private static HDrawingObject selected_drawing_object = new HDrawingObject(250, 250, 100);
        public static void roi_save(HDrawingObject dobj, HWindow hwin, string type)
        {
            try
            {
                double row, column, phi, length1, length2;
                HRegion region = new HRegion(dobj.GetDrawingObjectIconic());
                region.SmallestRectangle2(out row, out column, out phi, out length1, out length2);
                // 815 1324 236 146 680 4313 242 146
                
                HOperatorSet.GenRectangle2(out HObject rect, row, column, phi, length1, length2);
                MarkRegion = rect.Clone();
            }
            catch (HalconException ex)
            {
                displalyInfo.displayInfoMain(ex.Message);
            }
        }

        public static HObject MarkRegion = null;
        #endregion
        #region ROI区域
        public static void SaveRegion(e_Region region, e_CameraPlate cameraPlate)
        {
            var curRoiDir = roiDir + $"\\{GlobalVar.closeSave.CurrentTypeName}";
            if (!Directory.Exists(curRoiDir))
                Directory.CreateDirectory(curRoiDir);
            if (cameraPlate == e_CameraPlate.定位相机平台1 || cameraPlate == e_CameraPlate.定位相机平台2)
            {
                if (ROI1 == null)
                    ROI1 = new ROIRegion();
                if (draw_up_region_template1.Count > 0)
                {
                    switch (region)
                    {
                        case e_Region.切图区域:
                            ROI1.ROI_Region = draw_up_region_template1[0].GetDrawingObjectIconic();
                            HOperatorSet.WriteRegion(ROI1.ROI_Region, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                            HOperatorSet.ReadRegion(out HObject temp, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                            GlobalVar.imageDisplay1_obj(temp, "red");
                            visionProc.ROI_List[(int)cameraPlate].ROI_Region = ROI1.ROI_Region;
                            break;

                        case e_Region.模板区域:
                            ROI1.ROI_Template = draw_up_region_template1[0].GetDrawingObjectIconic();
                            HOperatorSet.WriteRegion(ROI1.ROI_Template, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");

                            visionProc.ROI_List[(int)cameraPlate].ROI_Template = ROI1.ROI_Template;

                            break;
                        case e_Region.直线区域1:
                            ROI1.ROI_Postion = draw_up_region_template1[0].GetDrawingObjectIconic();
                            visionProc.ROI_List[(int)cameraPlate].ROI_Postion = ROI1.ROI_Postion;
                            HOperatorSet.WriteRegion(ROI1.ROI_Postion, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                            break;
                        case e_Region.直线区域2:
                            ROI1.ROI_Postion2 = draw_up_region_template1[0].GetDrawingObjectIconic();
                            visionProc.ROI_List[(int)cameraPlate].ROI_Postion2 = ROI1.ROI_Postion2;
                            HOperatorSet.WriteRegion(ROI1.ROI_Postion2, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                            break;
                        case e_Region.抓圆区域:
                            ROI1.ROI_PosCircle = draw_up_region_template1[0].GetDrawingObjectIconic();
                            visionProc.ROI_List[(int)cameraPlate].ROI_PosCircle = ROI1.ROI_PosCircle;
                            HOperatorSet.WriteRegion(ROI1.ROI_PosCircle, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                            break;
                    }
                }
                else
                {
                    if (region == e_Region.模板区域 && ROI1.ROI_Template != null)
                    {
                        HOperatorSet.WriteRegion(ROI1.ROI_Template, roiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                        visionProc.ROI_List[(int)cameraPlate].ROI_Template = ROI1.ROI_Template;
                    }
                }
            }
            else if (cameraPlate == e_CameraPlate.图案相机平台1 || cameraPlate == e_CameraPlate.图案相机平台2)
            {
                if (ROI2 == null)
                    ROI2 = new ROIRegion();
                if (draw_up_region_template2.Count > 0)
                {
                    switch (region)
                    {
                        case e_Region.切图区域:
                            ROI2.ROI_Region = draw_up_region_template2[0].GetDrawingObjectIconic();
                            HOperatorSet.WriteRegion(ROI2.ROI_Region, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                            visionProc.ROI_List[(int)cameraPlate].ROI_Region = ROI2.ROI_Region;
                            break;

                        case e_Region.模板区域:
                            ROI2.ROI_Template = draw_up_region_template2[0].GetDrawingObjectIconic();
                            HOperatorSet.WriteRegion(ROI2.ROI_Template, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                            visionProc.ROI_List[(int)cameraPlate].ROI_Template = ROI2.ROI_Template;
                            break;
                        case e_Region.直线区域1:
                            ROI2.ROI_Postion = draw_up_region_template2[0].GetDrawingObjectIconic();
                            HOperatorSet.WriteRegion(ROI2.ROI_Postion, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                            visionProc.ROI_List[(int)cameraPlate].ROI_Postion = ROI2.ROI_Postion;
                            break;
                        case e_Region.直线区域2:
                            ROI2.ROI_Postion2 = draw_up_region_template2[0].GetDrawingObjectIconic();
                            HOperatorSet.WriteRegion(ROI2.ROI_Postion2, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                            visionProc.ROI_List[(int)cameraPlate].ROI_Postion2 = ROI2.ROI_Postion2;
                            break;
                        case e_Region.抓圆区域:
                            ROI2.ROI_PosCircle = draw_up_region_template2[0].GetDrawingObjectIconic();
                            HOperatorSet.WriteRegion(ROI2.ROI_PosCircle, curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                            visionProc.ROI_List[(int)cameraPlate].ROI_PosCircle = ROI2.ROI_PosCircle;
                            break;
                    }
                }
                else
                {
                    if (region == e_Region.模板区域 && ROI2.ROI_Template != null)
                    {
                        HOperatorSet.WriteRegion(ROI2.ROI_Template, roiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                        visionProc.ROI_List[(int)cameraPlate].ROI_Template = ROI2.ROI_Template;
                    }
                }

            }


        }
        public static void SaveRegion_M(e_RegionCheck region, e_CameraPlate cameraPlate)
        {
            var curRoiDir = roiDir + $"\\{GlobalVar.closeSave.CurrentTypeName}";
            if (!Directory.Exists(curRoiDir))
                Directory.CreateDirectory(curRoiDir);
            var strArr = Enum.GetNames(typeof(e_RegionCheck));
            if (cameraPlate == e_CameraPlate.检测相机平台1)
            {
                if (draw_up_region_template3.Count > 0)
                {
                    if (ROI_M_List1.Count < strArr.Length)
                    {
                        for (int m = ROI_M_List1.Count; m < strArr.Length; m++)
                        {
                            ROI_M_List1.Add(new HObject());
                        }
                    }
                    ROI_M_List1[(int)region] = draw_up_region_template3[0].GetDrawingObjectIconic();
                    HOperatorSet.WriteRegion(ROI_M_List1[(int)region], curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                }
            }
            else if (cameraPlate == e_CameraPlate.检测相机平台2)
            {
                if (draw_up_region_template3.Count > 0)
                {
                    if (ROI_M_List2.Count < strArr.Length)
                    {
                        for (int m = ROI_M_List2.Count; m < strArr.Length; m++)
                        {
                            ROI_M_List2.Add(new HObject());
                        }
                    }
                    ROI_M_List2[(int)region] = draw_up_region_template3[0].GetDrawingObjectIconic();
                    HOperatorSet.WriteRegion(ROI_M_List2[(int)region], curRoiDir + $"\\region_{(int)cameraPlate}_{(int)region}.hobj");
                }
            }

        }
        public static string roiDir = Application.StartupPath + "\\ROI";
        public static void ReadRegion()
        {
            var curRoiDir = roiDir + $"\\{GlobalVar.closeSave.CurrentTypeName}";
            if (!Directory.Exists(curRoiDir))
                Directory.CreateDirectory(curRoiDir);
            List<ROIRegion> resROI = new List<ROIRegion>();
            if (Directory.Exists(curRoiDir))
            {
                var files = Directory.GetFiles(curRoiDir);
                var arr = Enum.GetNames(typeof(e_CameraPlate));
                for (int m = 0; m < arr.Length; m++)
                {
                    ROIRegion curROI = new ROIRegion();
                    for (int i = 0; i < files.Length; i++)
                    {
                        var fNames = curRoiDir + $"\\region_{m}_";
                        var nLastIndex = files[i].IndexOf(fNames);
                        if (nLastIndex > -1)
                        {
                            var str_Index = files[i].Replace(fNames, "");
                            var nIndex = Convert.ToInt32(str_Index.Substring(0, 1));
                            var f = files[i];
                            HOperatorSet.ReadRegion(out HObject RoiRegion, f);
                            switch (nIndex)
                            {
                                case (int)e_Region.切图区域:
                                    curROI.ROI_Region = RoiRegion;
                                    break;
                                case (int)e_Region.模板区域:
                                    curROI.ROI_Template = RoiRegion;

                                    break;
                                case (int)e_Region.直线区域1:
                                    curROI.ROI_Postion = RoiRegion;
                                    break;
                                case (int)e_Region.直线区域2:
                                    curROI.ROI_Postion2 = RoiRegion;
                                    break;
                                case (int)e_Region.抓圆区域:
                                    curROI.ROI_PosCircle = RoiRegion;
                                    break;
                            }
                        }
                    }
                    resROI.Add(curROI);
                }
            }
            ROI_List = resROI;

        }
        public static List<HObject> ReadRegion_M(e_CameraPlate CameraPlate)
        {
            List<HObject> res = new List<HObject>();
            if (CameraPlate == e_CameraPlate.检测相机平台1 || CameraPlate == e_CameraPlate.检测相机平台2)
            {
                var strArr = Enum.GetNames(typeof(e_RegionCheck));
                for (int s = 0; s < strArr.Length; s++)
                {
                    res.Add(new HObject());
                }
            }
            var curRoiDir = roiDir + $"\\{GlobalVar.closeSave.CurrentTypeName}";
            if (!Directory.Exists(curRoiDir))
                Directory.CreateDirectory(curRoiDir);

            if (Directory.Exists(curRoiDir))
            {
                var files = Directory.GetFiles(curRoiDir);
                if (files.Length > 0)
                {
                    var cstr = $"\\region_{(int)CameraPlate}_";
                    files = files.ToList().Where(a => a.Contains(cstr)).ToArray();
                }
                for (int i = 0; i < files.Length; i++)
                {
                    var fNames = curRoiDir + $"\\region_{(int)CameraPlate}_";
                    var nLastIndex = files[i].IndexOf(fNames);
                    if (nLastIndex > -1)
                    {
                        var str_Index = files[i].Replace(fNames, "");
                        var nIndex = Convert.ToInt32(str_Index.Substring(0, 1));
                        var f = files[i];
                        HOperatorSet.ReadRegion(out HObject RoiRegion, f);
                        res[nIndex] = RoiRegion;
                    }
                }
            }

            return res;
        }
        #endregion
        public static  HObject ho_TemplateXLd;
        #region 模板匹配
        /// <summary>
        /// 创建模板
        /// </summary>
        /// <param name="TemplateParam_Create"></param>
        /// <returns></returns>
        public static HTuple CreateTemplate(HObject srcObject, HObject ROI_Template, TemplateParam templateParam, e_Camera camera)
        {

            try
            {
                HOperatorSet.ReduceDomain(srcObject, ROI_Template, out HObject regionReduce);
                HOperatorSet.CreateShapeModel(regionReduce, visionProc.TemplateParam_Create.nLevels,
                   // (new HTuple(visionProc.TemplateParam_Create.dAngleStart)).TupleRad(),
                   //(new HTuple(visionProc.TemplateParam_Create.dAngleExtent)).TupleRad(), 
                   //(new HTuple(visionProc.TemplateParam_Create.dAngleStep)).TupleRad(), 
                   templateParam.dAngleStart,
                   templateParam.dAngleExtent,
                   templateParam.dAngleStep,
                  "auto",
                  "use_polarity", templateParam.nContras, templateParam.nMinContrast, out HTuple TempleateModelId);
                HOperatorSet.GetShapeModelContours(out HObject ho_ModelContours1, TempleateModelId, 1);
                HOperatorSet.AreaCenter(ROI_Template, out HTuple hv_ModelRegionArea, out HTuple hv_RefRow, out HTuple hv_RefColumn);
                HOperatorSet.VectorAngleToRigid(0, 0, 0, hv_RefRow, hv_RefColumn, 0, out HTuple hv_HomMat2D);
                HOperatorSet.AffineTransContourXld(ho_ModelContours1, out ho_TemplateXLd, hv_HomMat2D);
                switch (camera)
                {
                    case e_Camera.定位相机:
                        GlobalVar.imageDisplay1_obj(ho_TemplateXLd, "yellow");
                        break;
                    case e_Camera.图案相机:
                        GlobalVar.imageDisplay2_obj(ho_TemplateXLd, "yellow");
                        break;
                    case e_Camera.检测相机:
                        GlobalVar.imageDisplay3_obj(ho_TemplateXLd, "yellow");
                        break;
                }

                return TempleateModelId;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 批量创建模板
        /// </summary>
        /// <param name="srcObject"></param>
        /// <returns></returns>
        public static List<HTuple> CreateTemplateList(HObject srcObject, List<HObject> ROI_Templates)
        {

            try
            {
                List<HTuple> templateIds = new List<HTuple>();
                for (int i = 0; i < ROI_Templates.Count; i++)
                {
                    templateIds.Add(new HTuple());
                    HOperatorSet.ReduceDomain(srcObject, ROI1.ROI_Template, out HObject regionReduce);
                    HOperatorSet.CreateShapeModel(regionReduce, visionProc.TemplateParam_Create.nLevels,
                       // (new HTuple(visionProc.TemplateParam_Create.dAngleStart)).TupleRad(),
                       //(new HTuple(visionProc.TemplateParam_Create.dAngleExtent)).TupleRad(), 
                       //(new HTuple(visionProc.TemplateParam_Create.dAngleStep)).TupleRad(), 
                       visionProc.TemplateParam_Create.dAngleStart,
                       visionProc.TemplateParam_Create.dAngleExtent,
                       visionProc.TemplateParam_Create.dAngleStep,
                       visionProc.TemplateParam_Create.eOptmization.ToString(),
                       visionProc.TemplateParam_Create.eMetric.ToString(), visionProc.TemplateParam_Create.nContras, visionProc.TemplateParam_Create.nMinContrast, out HTuple TempleateModelId);
                    HOperatorSet.GetShapeModelContours(out HObject ho_ModelContours1, TempleateModelId, 1);
                    HOperatorSet.AreaCenter(ROI1.ROI_Template, out HTuple hv_ModelRegionArea, out HTuple hv_RefRow, out HTuple hv_RefColumn);
                    HOperatorSet.VectorAngleToRigid(0, 0, 0, hv_RefRow, hv_RefColumn, 0, out HTuple hv_HomMat2D);
                    HOperatorSet.AffineTransContourXld(ho_ModelContours1, out HObject ho_TransContours, hv_HomMat2D);
                    GlobalVar.imageDisplay2_obj(ho_TransContours, "blue");
                    templateIds[i] = TempleateModelId;
                }


                return templateIds;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public static string TemplateRoiDir = Application.StartupPath + "\\Template";
        private static string TemplateMutilRoiDir = Application.StartupPath + "\\MutilTemplate";
        public static void SaveTemplateRegion(HTuple templateId, e_CameraPlate cameraPlate)
        {
            var curDir = TemplateRoiDir + $"\\{GlobalVar.closeSave.CurrentTypeName}";
            if (!Directory.Exists(curDir))
                Directory.CreateDirectory(curDir);
            visionProc.TemplateIds[(int)cameraPlate] = templateId;
            if (templateId != null && templateId.Type != HTupleType.EMPTY)
            {
                HOperatorSet.WriteShapeModel(templateId, $"{curDir}\\tempid_{(int)cameraPlate}.sbm");
            //    HOperatorSet.WriteShapeModel(templateId, $"{curDir}_{(int)cameraPlate}.sbm");
            }
            if (ho_TemplateXLd != null )
            {
                HOperatorSet.WriteObject(ho_TemplateXLd, $"{curDir}\\xld_{(int)cameraPlate}");
         //       HOperatorSet.WriteObject(ho_TemplateXLd,  $"{curDir}xld_{(int)cameraPlate}");
            }
        }
        public static void SaveMutilTemplateRegion(List<HTuple> templateList, int PlateIndex)
        {
            if (!Directory.Exists(roiDir))
                Directory.CreateDirectory(TemplateMutilRoiDir);
            for (int i = 0; i < templateList.Count; i++)
            {
                if (templateList[i] != null && templateList[i].Type != HTupleType.EMPTY)
                {
                    HOperatorSet.WriteShapeModel(templateList[i], TemplateMutilRoiDir + $"\\{GlobalVar.closeSave.CurrentTypeName}_{PlateIndex}_{i}.sbm");
                }
            }
        }
        /// <summary>
        /// 读取模板
        /// </summary>
        /// <returns></returns>
        public static void ReadTemplateRegion()
        {
            var tempList = new List<HTuple>();
            var tempxldList = new List<HObject>();
            var arr = Enum.GetValues(typeof(e_CameraPlate));
            for (int a = 0; a < arr.Length; a++)
            {
                tempList.Add(new HTuple());
                tempxldList.Add(new HObject());
            }
            var curDir = TemplateRoiDir + $"\\{GlobalVar.closeSave.CurrentTypeName}";
            if (Directory.Exists(curDir))
            {
                var files = Directory.GetFiles(curDir);
                for (int i = 0; i < files.Length; i++)
                {
                    var firstStr =  $"{curDir}\\tempid_";
                    // var firstStr = $"{curDir}_";
                    var nIndex = files[i].IndexOf(firstStr);
                    if (nIndex > -1)
                    {
                        var resStr = files[i].Replace(firstStr, "");
                        var num = Convert.ToInt32(resStr.Substring(nIndex, 1));
                        HOperatorSet.ReadShapeModel(files[i], out HTuple hTuple);
                        tempList[num] = hTuple;
                    }
                    var xldfirstStr = $"{curDir}\\xld_";
                 //   var xldfirstStr = $"{curDir}xld_";
                    var n_xldIndex = files[i].IndexOf(xldfirstStr);
                    if (n_xldIndex > -1)
                    {
                        var resStr = files[i].Replace(xldfirstStr, "");
                        var num = Convert.ToInt32(resStr.Substring(n_xldIndex, 1));
                        HOperatorSet.ReadObject(out HObject tempxld, files[i]);
                        tempxldList[num] = tempxld;
                    }
                }
            }
            TemplateIds = tempList;
            Template_xlds = tempxldList;
        }

        /// <summary>
        /// 读取模板
        /// </summary>
        /// <returns></returns>
        public static void ReadMutilTemplateRegion()
        {
            var tempList = new List<HTuple>();

            if (Directory.Exists(TemplateMutilRoiDir))
            {
                var files = Directory.GetFiles(TemplateRoiDir);
                for (int m = 0; m < MulitPlateCount * EverPlateTemplatCount; m++)
                {
                    tempList.Add(new HTuple());
                }
                for (int i = 0; i < files.Length; i++)
                {
                    var firstStr = TemplateRoiDir + $"\\{GlobalVar.closeSave.CurrentTypeName}_";
                    var nIndex = files[i].IndexOf(firstStr);
                    if (nIndex > -1)//读出是平台几
                    {
                        var resStr = files[i].Replace(firstStr, "");
                        var plateIndex = Convert.ToInt32(resStr.Substring(nIndex, 1));
                        var chilidStr = TemplateRoiDir + $"\\{GlobalVar.closeSave.CurrentTypeName}_{plateIndex}_";
                        var IndexStr = files[i].Replace(chilidStr, "").Replace(".sbm", "");
                        nIndex = Convert.ToInt32(IndexStr);
                        if (nIndex > -1)//读出是第几个图案
                        {
                            HOperatorSet.ReadShapeModel(files[i], out HTuple hTuple);
                            tempList[plateIndex * EverPlateTemplatCount + nIndex] = hTuple;
                        }

                    }
                }
            }
            TemplateIds = tempList;
        }
        /// <summary>
        /// 多平台平台数量
        /// </summary>
        public static int MulitPlateCount = 2;
        /// <summary>
        /// 每个平台多少个模板
        /// </summary>
        public static int EverPlateTemplatCount = 15;
        public static TemplateParam TemplateParam_Create = new TemplateParam();

        public static TemplateFindParam TemplateParam_Find = new TemplateFindParam();

        /// <summary>
        /// 检测模板匹配结果
        /// </summary>
        /// <returns></returns>
        public static Result_Template findTemplate(HObject SrcImage, HTuple TempleateModel, TemplateFindParam TemplateParam_Find, HObject ROI_Region)
        {

            if (TempleateModel!=null&&TempleateModel.Type == HTupleType.EMPTY)
                return null;
            HOperatorSet.ReduceDomain(SrcImage, ROI_Region, out HObject region_OK);
            HTuple dColumn, dRow, dAngle, dScore;
            if (TempleateModel==null)
            {
                return null;
            }
            HOperatorSet.FindShapeModel(region_OK, TempleateModel, TemplateParam_Find.dAngleStart, TemplateParam_Find.dAngleExtent,
                    TemplateParam_Find.dMinScore, 1,
                    TemplateParam_Find.dMaxOverlap, "least_squares", TemplateParam_Find.nLevels,
                    0.75, out dRow, out dColumn, out dAngle, out dScore);
            if (dRow.Type != HTupleType.EMPTY)
            {
                var result = new Result_Template { dRow = dRow, dColumn = dColumn, dAngle = dAngle.D, dScore = dScore };

                return result;
            }
            return null;
        }
        public static ROIRegion ROI3;
        public static ROIRegion ROI2;
        /// <summary>
        /// 定位相机的各个ROI
        /// </summary>
        public static ROIRegion ROI1;
        #region 创建测量卡尺
        public static HObject findMeasureLine(HObject SrcImage,LindFindParam LineParam_Find, HObject lineObject)
        {
            try
            {
                HOperatorSet.CreateMetrologyModel(out HTuple MetrologyHandel);

                HOperatorSet.SmallestRectangle2(lineObject, out HTuple row1, out HTuple col1, out HTuple phi1, out HTuple dHalfLength, out HTuple dHalfWidth);
                HOperatorSet.GenRectangle2(out HObject temp, row1, col1, phi1, dHalfLength, 1);
                HOperatorSet.GetRegionPoints(temp, out HTuple rows, out HTuple cols);
                var pLength = rows.LArr.Length;
                var angle = phi1.D / Math.PI * 180;
                //HOperatorSet.AddMetrologyObjectLineMeasure(MetrologyHandel, col1.D - dHalfLength*Math.Cos(angle), row1.D + dHalfLength * Math.Sin(angle),
                //col1.D + dHalfLength * Math.Cos(angle), row1.D - dHalfLength * Math.Sin(angle), LineParam_Find.dLength, LineParam_Find.dWidth, 1, LineParam_Find.Threshold, new HTuple(), new HTuple(), out HTuple Index);
                HOperatorSet.AddMetrologyObjectLineMeasure(MetrologyHandel, rows.LArr[0], cols.LArr[0], rows.LArr[pLength - 1], cols.LArr[pLength - 1], LineParam_Find.dLength, LineParam_Find.dWidth, 1, LineParam_Find.Threshold, new HTuple(), new HTuple(), out HTuple Index);
                HOperatorSet.ApplyMetrologyModel(SrcImage, MetrologyHandel);
                HOperatorSet.GetMetrologyObjectMeasures(out HObject mes_Hobject, MetrologyHandel, "all", "all", out HTuple hv_Row, out HTuple hv_Column);
                GlobalVar.imageDisplay3_obj(mes_Hobject, "orange");
                HOperatorSet.GetMetrologyObjectResultContour(out HObject ho_Contours, MetrologyHandel, "all", "all", 1.5);
                HOperatorSet.GetMetrologyObjectResult(MetrologyHandel, "all", "all", "result_type","all_param",out HTuple hParam);
                
                GlobalVar.imageDisplay3_obj(ho_Contours, "red");
                HOperatorSet.ClearMetrologyModel(MetrologyHandel);
                HOperatorSet.GenCrossContourXld(out HObject crossObj, hv_Row, hv_Column, 2, 0);
                GlobalVar.imageDisplay3_obj(crossObj, "green");
                if (hParam.Type != HTupleType.EMPTY && hParam.DArr.Length == 4)
                {
                    HOperatorSet.GenRegionLine(out HObject resObject, hParam.DArr[0], hParam.DArr[1], hParam.DArr[2], hParam.DArr[3]);
                    GlobalVar.imageDisplay3_obj(resObject, "black");
                    return resObject;
                }
               
                else
                    return null;
            } catch (Exception ex)
            {
                return null;
            }
           
        }
        public static HObject findLine(HObject SrcImage, LindFindParam LineParam_Find, Result_Template tResult, HObject lineObject)
        {
            try
            {
                if(tResult!=null)
                {
                
                    HOperatorSet.HomMat2dIdentity(out HTuple homMat2d);
                 //   HOperatorSet.SmallestRectangle1(lineObject, out HTuple rowL, out HTuple colL, out HTuple rowL2, out HTuple colL2);
                    //var colTrans_soure =(colL.D + colL2.D) / 2 ;
                    //var rowTrans_soure =(rowL.D + rowL2.D) / 2 ;
                    HOperatorSet.SmallestRectangle2(lineObject, out HTuple rowL, out HTuple colL, out HTuple phi, out HTuple rowL2, out HTuple colL2);
                    var colTrans_soure = colL.D ;
                    var rowTrans_soure = rowL.D ;
                    GlobalVar.imageDisplay1_obj(lineObject, "red");
                    #region 将模板结果坐标    Cos（结果角度+相对角度）*R       Sin（结果角度+相对角度）*R
                    var curAngle = tResult.dAngle / Math.PI * 180 + LineParam_Find.Angle;
                    var infos=CaculateNextPoint(new PointF() { X = (float)tResult.dColumn, Y = (float)tResult.dRow }, curAngle, LineParam_Find.R);
                    var NextPoint = new PointF() { X = -1,Y=-1 };
                    if(infos.Count>1)
                    {
                        NextPoint.X =(float) infos[0];
                        NextPoint.Y = (float)infos[1];
                    }
                    HOperatorSet.GenCrossContourXld(out HObject cross, NextPoint.Y, NextPoint.X, 100, 0);
                    GlobalVar.imageDisplay1_obj(cross, "orange");
                    var Xran =  colTrans_soure- NextPoint.X;
                    var Yran =   rowTrans_soure- NextPoint.Y;
                    HOperatorSet.HomMat2dTranslate(homMat2d,-Yran, -Xran,out HTuple homMat2dTrans);
                 HOperatorSet.AffineTransRegion(lineObject, out HObject CurlineObject, homMat2dTrans, "nearest_neighbor");
         //           HOperatorSet.MoveRegion(lineObject,out HObject CurlineObject, NextPoint.Y, NextPoint.X);
                    #endregion
                    #region 先计算新的模板      与原模板在平移上的差别   与原模板在旋转上的差别
                    var y = tResult.dRow - LineParam_Find.VarY;
                    var x = tResult.dColumn - LineParam_Find.VarX;
                    //HOperatorSet.HomMat2dTranslate(homMat2d, y, x, out HTuple homMat2dTrans);
                   
                    #endregion
                    #region 平移
                 //   HOperatorSet.AffineTransRegion(lineObject, out HObject CurlineObject, homMat2dTrans, "nearest_neighbor");
                    GlobalVar.imageDisplay1_obj(CurlineObject, "orange");
                    //HOperatorSet.SmallestRectangle1(CurlineObject, out HTuple row1L, out HTuple co1lL, out HTuple o1wL2, out HTuple co1lL2);
                    #endregion
                    #region  旋转
                    HOperatorSet.SmallestRectangle1(CurlineObject, out HTuple rowR, out HTuple colR, out HTuple rowR2, out HTuple colR2);
                    var colTrans_soure2 = (colR.D + colR2.D) / 2;
                    var rowTrans_soure2 = (rowR.D + rowR2.D) / 2;
                    HOperatorSet.HomMat2dRotate(homMat2d, tResult.dAngle,rowTrans_soure2, colTrans_soure2,out HTuple homMat2dRotate);
                    HOperatorSet.AffineTransRegion(CurlineObject, out HObject newlineObject, homMat2dRotate, "nearest_neighbor");
              //      GlobalVar.imageDisplay1_obj(newlineObject, "orange");
                    #endregion
                    

                    HOperatorSet.CreateMetrologyModel(out HTuple MetrologyHandel);

                    HOperatorSet.SmallestRectangle2(newlineObject, out HTuple row1, out HTuple col1, out HTuple phi1, out HTuple dHalfLength, out HTuple dHalfWidth);
                    HOperatorSet.GenRectangle2(out HObject temp, row1, col1, phi1, dHalfLength, 1);
                    HOperatorSet.GetRegionPoints(temp, out HTuple rows, out HTuple cols);
                    var pLength = rows.LArr.Length;
                    var angle = phi1.D / Math.PI * 180;
                    //HOperatorSet.AddMetrologyObjectLineMeasure(MetrologyHandel, col1.D - dHalfLength*Math.Cos(angle), row1.D + dHalfLength * Math.Sin(angle),
                    //col1.D + dHalfLength * Math.Cos(angle), row1.D - dHalfLength * Math.Sin(angle), LineParam_Find.dLength, LineParam_Find.dWidth, 1, LineParam_Find.Threshold, new HTuple(), new HTuple(), out HTuple Index);
                    HOperatorSet.AddMetrologyObjectLineMeasure(MetrologyHandel, rows.LArr[0], cols.LArr[0], rows.LArr[pLength - 1], cols.LArr[pLength - 1], LineParam_Find.dLength, LineParam_Find.dWidth, 1, LineParam_Find.Threshold, new HTuple(), new HTuple(), out HTuple Index);
                    HOperatorSet.ApplyMetrologyModel(SrcImage, MetrologyHandel);
                    HOperatorSet.GetMetrologyObjectMeasures(out HObject mes_Hobject, MetrologyHandel, "all", "all", out HTuple hv_Row, out HTuple hv_Column);
                    GlobalVar.imageDisplay1_obj(mes_Hobject, "orange");
                    HOperatorSet.GetMetrologyObjectResultContour(out HObject ho_Contours, MetrologyHandel, "all", "all", 1.5);
                    HOperatorSet.GetMetrologyObjectResult(MetrologyHandel, "all", "all", "result_type", "all_param", out HTuple hParam);

                    GlobalVar.imageDisplay1_obj(ho_Contours, "red");
                    HOperatorSet.ClearMetrologyModel(MetrologyHandel);
                    HOperatorSet.GenCrossContourXld(out HObject crossObj, hv_Row, hv_Column, 2, 0);
                    GlobalVar.imageDisplay1_obj(crossObj, "green");
                    if (hParam.Type != HTupleType.EMPTY && hParam.DArr.Length == 4)
                    {
                        HOperatorSet.GenRegionLine(out HObject resObject, hParam.DArr[0], hParam.DArr[1], hParam.DArr[2], hParam.DArr[3]);
                        GlobalVar.imageDisplay1_obj(resObject, "black");
                        return resObject;
                    }
                    else
                        return null;
                }
               

                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
        public static HObject findCirclde(HObject SrcImage, CircleFindParam Param_Find, Result_Template tResult,HObject CircleObject)
        {
            try
            {
                HOperatorSet.HomMat2dIdentity(out HTuple homMat2d);

                HOperatorSet.SmallestRectangle2(CircleObject, out HTuple rowL, out HTuple colL, out HTuple phi, out HTuple rowL2, out HTuple colL2);
                var colTrans_soure = colL.D;
                var rowTrans_soure = rowL.D;
                GlobalVar.imageDisplay1_obj(CircleObject, "red");
                #region 将模板结果坐标    Cos（结果角度+相对角度）*R       Sin（结果角度+相对角度）*R
                var curAngle = tResult.dAngle / Math.PI * 180 + Param_Find.Angle;
                var infos = CaculateNextPoint(new PointF() { X = (float)tResult.dColumn, Y = (float)tResult.dRow }, curAngle, Param_Find.R);
                var NextPoint = new PointF() { X = -1, Y = -1 };
                if (infos.Count > 1)
                {
                    NextPoint.X = (float)infos[0];
                    NextPoint.Y = (float)infos[1];
                }
                HOperatorSet.GenCrossContourXld(out HObject cross, NextPoint.Y, NextPoint.X, 100, 0);
                GlobalVar.imageDisplay1_obj(cross, "orange");
                var Xran = colTrans_soure - NextPoint.X;
                var Yran = rowTrans_soure - NextPoint.Y;
                HOperatorSet.HomMat2dTranslate(homMat2d,- Yran, -Xran, out HTuple homMat2dTrans);
               
                #endregion
                #region 先计算新的模板      与原模板在平移上的差别   与原模板在旋转上的差别
                var y = tResult.dRow - Param_Find.VarY;
                var x = tResult.dColumn - Param_Find.VarX;

                #endregion
                #region 平移
                HOperatorSet.AffineTransRegion(CircleObject, out HObject CurlineObject, homMat2dTrans, "nearest_neighbor");
                GlobalVar.imageDisplay1_obj(CurlineObject, "orange");
                #endregion
                #region  旋转
                HOperatorSet.SmallestRectangle1(CurlineObject, out HTuple rowR, out HTuple colR, out HTuple rowR2, out HTuple colR2);
                var colTrans_soure2 = (colR.D + colR2.D) / 2;
                var rowTrans_soure2 = (rowR.D + rowR2.D) / 2;
                HOperatorSet.HomMat2dRotate(homMat2d, tResult.dAngle, rowTrans_soure2, colTrans_soure2, out HTuple homMat2dRotate);
                HOperatorSet.AffineTransRegion(CurlineObject, out HObject newCircleObject, homMat2dRotate, "nearest_neighbor");
                //      GlobalVar.imageDisplay1_obj(newlineObject, "orange");
                #endregion
                HOperatorSet.CreateMetrologyModel(out HTuple MetrologyHandel);

                HOperatorSet.SmallestRectangle2(newCircleObject, out HTuple row1, out HTuple col1, out HTuple phi1, out HTuple dHalfLength, out HTuple dHalfWidth);
                //HOperatorSet.GenRectangle2(out HObject temp, row1, col1, phi1, dHalfLength, 1);
                //HOperatorSet.GetRegionPoints(temp, out HTuple rows, out HTuple cols);
                //var pLength = rows.LArr.Length;
                var angle = phi1.D / Math.PI * 180;
                if (string.IsNullOrEmpty(Param_Find.point_order))
                {
                    var hv_genParamName = new HTuple();
                    hv_genParamName[0] = "start_phi";
                    hv_genParamName[1] = "end_phi";

                    var hv_genParamValue = new HTuple();
                    hv_genParamValue[0] = (new HTuple(Param_Find.dStartAngle)).TupleRad();
                    hv_genParamValue[1] = (new HTuple(Param_Find.dEndAngle)).TupleRad();
 
                    HOperatorSet.AddMetrologyObjectCircleMeasure(MetrologyHandel, row1, col1, Param_Find.dRadius,
                                 Param_Find.dHalfLength, Param_Find.dHalfWidth, Param_Find.dSigma, Param_Find.dThreshold, hv_genParamName, hv_genParamValue, out HTuple HIndex);
                }
                else

                {
                   var  hv_genParamName = new HTuple();
                    hv_genParamName[0] = "start_phi";
                    hv_genParamName[1] = "end_phi";
                    hv_genParamName[2] = "point_order";
                    var hv_genParamValue = new HTuple();
                    hv_genParamValue[0] = (new HTuple(Param_Find.dStartAngle)).TupleRad() ;
                    hv_genParamValue[1] = (new HTuple(Param_Find.dEndAngle)).TupleRad();
                    hv_genParamValue[2] = Param_Find.point_order;

                    var value_arr = new HTuple[3] { Param_Find.point_order, Param_Find.dStartAngle/180*Math.PI, Param_Find.dEndAngle / 180 * Math.PI };
                    HOperatorSet.AddMetrologyObjectCircleMeasure(MetrologyHandel, row1.D, col1.D, Param_Find.dRadius,
                                  Param_Find.dHalfLength, Param_Find.dHalfWidth, Param_Find.dSigma, Param_Find.dThreshold, hv_genParamName, hv_genParamValue, out HTuple HIndex);
                }
                HOperatorSet.ApplyMetrologyModel(SrcImage, MetrologyHandel);
                HOperatorSet.GetMetrologyObjectMeasures(out HObject mes_Hobject, MetrologyHandel, "all", "all", out HTuple hv_Row, out HTuple hv_Column);
                GlobalVar.imageDisplay1_obj(mes_Hobject, "orange");
                HOperatorSet.GetMetrologyObjectResultContour(out HObject ho_Contours, MetrologyHandel, "all", "all", 1.5);
                //HOperatorSet.GetMetrologyObjectResult(MetrologyHandel, "all", "all", "result_type", "all_param", out HTuple hParam);

                GlobalVar.imageDisplay1_obj(ho_Contours, "red");
                HOperatorSet.ClearMetrologyModel(MetrologyHandel);
                HOperatorSet.GenCrossContourXld(out HObject crossObj, hv_Row, hv_Column, 2, 0);
                GlobalVar.imageDisplay1_obj(crossObj, "green");

                if (hv_Row.Type != HTupleType.EMPTY )
                {
                    HOperatorSet.GenContourPolygonXld(out HObject circle2, hv_Row, hv_Column);
                    HOperatorSet.FitCircleContourXld(circle2, "geotukey", -1, 0, 0, 3, 2, out HTuple row, out HTuple col, out HTuple radius, out HTuple startPhi, out HTuple endPhi, out HTuple pointOrder);
                    HOperatorSet.GenCircle(out HObject resObject, row.D, col.D, radius.D);
                    GlobalVar.imageDisplay1_obj(resObject, "black");
                    return resObject;
                }

                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
        public static VisionPos findCircleCheck(HObject SrcImage, CircleFindParam Param_Find,  HObject CircleRegion)
        {
            try
            {
                HOperatorSet.CreateMetrologyModel(out HTuple MetrologyHandel);
                HOperatorSet.SmallestRectangle2(CircleRegion, out HTuple row1, out HTuple col1, out HTuple phi1, out HTuple dHalfLength, out HTuple dHalfWidth);
                var angle = phi1.D / Math.PI * 180;
                if (string.IsNullOrEmpty(Param_Find.point_order))
                {
                    var hv_genParamName = new HTuple();
                    hv_genParamName[0] = "start_phi";
                    hv_genParamName[1] = "end_phi";

                    var hv_genParamValue = new HTuple();
                    hv_genParamValue[0] = (new HTuple(Param_Find.dStartAngle)).TupleRad();
                    hv_genParamValue[1] = (new HTuple(Param_Find.dEndAngle)).TupleRad();

                    HOperatorSet.AddMetrologyObjectCircleMeasure(MetrologyHandel, row1, col1, Param_Find.dRadius,
                                 Param_Find.dHalfLength, Param_Find.dHalfWidth, Param_Find.dSigma, Param_Find.dThreshold, hv_genParamName, hv_genParamValue, out HTuple HIndex);
                }
                else

                {
                    var hv_genParamName = new HTuple();
                    hv_genParamName[0] = "start_phi";
                    hv_genParamName[1] = "end_phi";
                    hv_genParamName[2] = "point_order";
                    var hv_genParamValue = new HTuple();
                    hv_genParamValue[0] = (new HTuple(Param_Find.dStartAngle)).TupleRad();
                    hv_genParamValue[1] = (new HTuple(Param_Find.dEndAngle)).TupleRad();
                    hv_genParamValue[2] = Param_Find.point_order;

                    var value_arr = new HTuple[3] { Param_Find.point_order, Param_Find.dStartAngle / 180 * Math.PI, Param_Find.dEndAngle / 180 * Math.PI };
                    HOperatorSet.AddMetrologyObjectCircleMeasure(MetrologyHandel, row1.D, col1.D, Param_Find.dRadius,
                                  Param_Find.dHalfLength, Param_Find.dHalfWidth, Param_Find.dSigma, Param_Find.dThreshold, hv_genParamName, hv_genParamValue, out HTuple HIndex);
                }
                HOperatorSet.ApplyMetrologyModel(SrcImage, MetrologyHandel);
                HOperatorSet.GetMetrologyObjectMeasures(out HObject mes_Hobject, MetrologyHandel, "all", "all", out HTuple hv_Row, out HTuple hv_Column);
                GlobalVar.imageDisplay3_obj(mes_Hobject, "orange");
                HOperatorSet.GetMetrologyObjectResultContour(out HObject ho_Contours, MetrologyHandel, "all", "all", 1.5);
                //HOperatorSet.GetMetrologyObjectResult(MetrologyHandel, "all", "all", "result_type", "all_param", out HTuple hParam);

                GlobalVar.imageDisplay3_obj(ho_Contours, "red");
                HOperatorSet.ClearMetrologyModel(MetrologyHandel);
                HOperatorSet.GenCrossContourXld(out HObject crossObj, hv_Row, hv_Column, 2, 0);
                GlobalVar.imageDisplay3_obj(crossObj, "green");
                HOperatorSet.FitCircleContourXld(ho_Contours, "geotukey", -1, 0, 0, 3, 2, out HTuple row, out HTuple col, out HTuple radius, out HTuple startPhi, out HTuple endPhi, out HTuple pointOrder);
                if (row.Type != HTupleType.EMPTY)
                {
                    HOperatorSet.GenCircle(out HObject resObject, row.D, col.D, radius.D);
                    GlobalVar.imageDisplay3_obj(resObject, "black");
                    return new VisionPos() { X = col.D ,Y=row.D,R=radius.D};
                }

                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
        /// <summary>
        /// 计算两点中点坐标+角度（以第一个点为基准）
        /// </summary>
        /// <param name="basePoint"></param>
        /// <param name="last"></param>
        /// <returns></returns>
        public static VisionPos CalcuteCenterPointAngle(PointF basePoint,PointF last )
        {
            var centerX = (basePoint.X + last.X) / 2;
            var centerY = (basePoint.Y + last.Y) / 2;
            var Xvar = last.X- basePoint.X;
            var Yvar = last.Y- basePoint.Y;
            var Angle = 0.0;
            if (Xvar == 0)
                Angle = 90;
            else
                Angle=Math.Atan(Yvar / Xvar) / Math.PI * 180;
            return new VisionPos() { X = centerX, Y = centerY, R = Angle };

        }
        public static VisionPos intersection_Line(HObject line1, HObject line2)
        {
            try
            {
                if (line1 != null && line2 != null)
                {
                   
                    HOperatorSet.GetRegionPoints(line1, out HTuple row1, out HTuple col1);
                    var pLength1 = row1.LArr.Length;
                    HOperatorSet.GetRegionPoints(line2, out HTuple row2, out HTuple col2);
                    var pLength2 = row2.LArr.Length;
                    HOperatorSet.IntersectionLines(
                        row1.LArr[0], col1.LArr[0], row1.LArr[pLength1 - 1], col1.LArr[pLength1 - 1],
                        row2.LArr[0], col2.LArr[0], row2.LArr[pLength2 - 1], col2.LArr[pLength2 - 1],
                        out HTuple row, out HTuple col, out HTuple IsOverlap);
                      if(row.DArr.Length==1)
                    {
                        HOperatorSet.GenCrossContourXld(out HObject crossing, row, col, 120, 0);
                        GlobalVar.imageDisplay3_obj(crossing, "green");
                        HOperatorSet.LineOrientation(row1.LArr[0], col1.LArr[0], row1.LArr[pLength1 - 1], col1.LArr[pLength1 - 1], out HTuple phi);
                        var angle = 0.0;
                        if(phi.Type!=HTupleType.EMPTY)
                        {
                            angle =phi.D;
                        }
                        return new VisionPos() { X = col.DArr[0], Y = row.DArr[0],R= angle };
                    }
                    else
                        return null;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
        #endregion
        #endregion
    }
    public class VisionPostion
    {
        /// <summary>
        /// 灰度最小
        /// </summary>
        public double grayMin1 { get; set; } = 0;
        /// <summary>
        /// 灰度最大
        /// </summary>
        public double grayMax1 { get; set; } = 60;
        /// <summary>
        /// 面积最大
        /// </summary>
        public double areaMax1 { get; set; } = 20000;
        /// <summary>
        /// 面积最小
        /// </summary>
        public double areaMin1 { get; set; } = 2000;
       
        /// <summary>
        /// 灰度最小
        /// </summary>
        public double grayMin2 { get; set; } = 0;
        /// <summary>
        /// 灰度最大
        /// </summary>
        public double grayMax2 { get; set; } = 60;
        /// <summary>
        /// 面积最大
        /// </summary>
        public double areaMax2 { get; set; } = 20000;
        /// <summary>
        /// 面积最小
        /// </summary>
        public double areaMin2 { get; set; } = 2000;
        /// <summary>
        /// X像素单量
        /// </summary>
        public double pixXReal { get; set; }
        /// <summary>
        /// Y像素单量
        /// </summary>
        public double pixYReal { get; set; }
        /// <summary>
        /// 平台1X坐标(像素)
        /// </summary>
        public double RealX1 { get; set; }
        /// <summary>
        ///  平台1Y坐标(像素)
        /// </summary>
        public double RealY1 { get; set; }
        /// <summary>
        ///  平台1R坐标(像素)
        /// </summary>
        public double RealR1 { get; set; }

        /// <summary>
        /// 平台2X坐标(像素)
        /// </summary>
        public double RealX2 { get; set; }
        /// <summary>
        ///  平台2Y坐标(像素)
        /// </summary>
        public double RealY2 { get; set; }
        /// <summary>
        ///  平台2R坐标(像素)
        /// </summary>
        public double RealR2 { get; set; }
    }
    public class ROIRegion
    {
        
        public HObject ROI_Template { get; set; }
        public HObject ROI_Region { get; set; }
        public HObject ROI_Postion { get; set; }
        public HObject ROI_Postion2 { get; set; }
        public HObject ROI_PosCircle { get; set; }
    }
    public class ImageReult
    {
        public HObject sourceImage { get; set; }
        public HObject tempxld { get; set; }
        public HObject crossing { get; set; }
        public string msg { get; set; }
    }
    public enum e_Region
    {
        切图区域,//
        模板区域,//模板
        直线区域1,//预留
        直线区域2,
        抓圆区域
    }
    public enum e_RegionCheck
    {
        切图区域,//识别有误
        撕膜区域1,//识别撕膜效果
        撕膜区域2,
        撕膜区域3,
        检测区域1,//
        检测区域2,//
        检测区域3,//
        检测区域4,//
        找圆区域1,
        找圆区域2,
        直线区域1,
        直线区域2,
    }
    public class Result_Template
    {

        /// <summary>
        /// 模板中心行坐标
        /// </summary>
        public double dRow { get; set; }
        /// <summary>
        /// 模板中心列坐标
        /// </summary>
        public double dColumn { get; set; }
        /// <summary>
        /// 模板角度
        /// </summary>
        public double dAngle { get; set; }

        /// <summary>
        /// 模板的匹配分数
        /// </summary>
        public double dScore { get; set; }
        /// <summary>
        /// 模板ID索引值
        /// </summary>
        public int nModelIndex { get; set; }

    }
    /// <summary>
    /// 亚像素
    /// </summary>
    public enum e_SubPixel
    {
        least_squares,
        none,
        interpolation,
        least_squares_high,
        least_squares_very_high,
    }
    [Serializable]
    public class TemplateFindParam
    {
        ///image, hv_ModelID, 0,360, 0.4, 1, 0.5, "least_squares",5, 0.75, out hv_Row, out hv_Column, out hv_Angle, out hv_Score
        /// <summary>
        /// 起始角度
        /// </summary>
        public double dAngleStart { get; set; } = 0;
        /// <summary>
        /// 角度范围
        /// </summary>
        public double dAngleExtent { get; set; } = 180;

        /// <summary>
        /// 最小匹配度
        /// </summary>
        public double dMinScore { get; set; } = 0.4;
        /// <summary>
        /// 最大匹配个数
        /// </summary>
        public int nNumMatches { get; set; } = 1;
        /// <summary>
        /// 两个模板之间最多重叠系数 0-1   0表示不重叠   1表示全重叠
        /// </summary>
        public double dMaxOverlap { get; set; } = 0.5;
        /// <summary>
        /// 是否使用亚像素精度提取
        /// </summary>
        public e_SubPixel eSubPixel { get; set; } = e_SubPixel.least_squares;
        /// <summary>
        /// 金字塔   无auto
        /// </summary>
        public int nLevels { get; set; } = 5;
        /// <summary>
        /// 贪婪程度0.0-1.0
        /// </summary>
        public double dGreediness { get; set; } = 0.75;
        public double xMax { get; set; }
        public double xMin { get; set; }
        public double yMax { get; set; }
        public double yMin { get; set; }
        public double rMax { get; set; }
        public double rMin { get; set; }
     

    }
    public enum e_Line
        {
        直线1,
        直线2
        }
    public enum e_Circle
    {
        找圆1,
        找圆2
    }
    public class LindFindParam
    {
     
        /// <summary>
        /// 卡尺长
        /// </summary>
        public double dLength { get; set; } = 0;
        /// <summary>
        /// 卡尺宽
        /// </summary>
        public double dWidth { get; set; } = 180;
        /// <summary>
        ///
        /// </summary>
        public double dSigma { get; set; } = 1;
        public int Threshold { get; set; } = 1;
        public double VarX { get; set; }
        public double VarY { get; set; }
        public double R { get; set; }
        public double Angle { get; set; }

    }
    public class CircleFindParam
    {
        public double dStartAngle{ get; set; }
        public double dEndAngle { get; set; }
        public double dLength { get; set; }
        public double dRadius { get; set; }
        public double dHalfLength { get; set; }
        public double dHalfWidth { get; set; }
        public double dSigma { get; set; }
        public double dThreshold { get; set; }
        public string point_order { get; set; }
        public double VarX { get; set; }
        public double VarY { get; set; }
        public double R { get; set; }
        public double Angle { get; set; }
    }
    public class CutParma
    {
        public int GaryMin { get; set; }
        public int GaryMax { get; set; }
        public int AreaMin { get; set; }
        public int AreaMax { get; set; }
    }
    public class MeasureParma
    {
        public int RegionIndex { get; set; }
        /// <summary>
        /// 高斯平滑的Sigma   默认值：1.0    最小增量：0.01   0.4≤Sigma≤100
        /// </summary>
        public double dSigma { get; set; }
        /// <summary>
        /// 最小边缘幅度     30.0         最小增量：0.5       1≤阈值≤255（lin）
        /// </summary>
        public double dThreshold { get; set; }
        /// <summary>
        /// /确定如何分组到边缘对的边缘灰度值转换类型     默认值：’all’
        /// </summary>
        public string Transition { get; set; }
        /// <summary>
        ///选择边缘对    默认值：all
        /// </summary>
        public string Select { get; set; }
        public string Interpolation { get; set; }
        /// <summary>
        /// 间距最大
        /// </summary>
        public double distanceMax { get; set; }
        /// <summary>
        /// 间距最小
        /// </summary>
        public double distanceMin { get; set; }
        /// <summary>
        /// 符合要求的测量对数量
        /// </summary>
        public int nPar { get; set; }
    }
    [Serializable]
    public class  TemplateParam
    {
        /// <summary>
        /// 金字塔级别
        /// </summary>
        public int nLevels { get; set; } = 5;
        /// <summary>
        /// 起始角度
        /// </summary>
        public double dAngleStart { get; set; } = 0;
        /// <summary>
        /// 角度范围
        /// </summary>
        public double dAngleExtent { get; set; } =180;
        /// <summary>
        /// 角度步长
        /// </summary>
        public double dAngleStep { get; set; } = 0;
        /// <summary>
        /// 模板优化和创建方法
        /// </summary>
        public e_Optmization eOptmization { get; set; } = e_Optmization.none;
        /// <summary>
        /// 对比度
        /// </summary>
        public int nContras { get; set; }
        /// <summary>
        /// 最小对比度
        /// </summary>
        public int nMinContrast { get; set; }
        /// <summary>
        /// 匹配方法
        /// </summary>
        public e_Metric eMetric { get; set; } = e_Metric.use_polarity;

    }
    /// <summary>
    /// 匹配方法
    /// </summary>
    public enum e_Metric
    {
        use_polarity,
        ignore_global_polarity,
        ignore_local_polarity,
        ignore_color_polarity,
    }
    /// <summary>
    /// 模板优化和创建方法
    /// </summary>
    public enum e_Optmization
    {
        auto,
        none,
        point_reduction_low,
        point_reduction_medium,
        point_reduction_high,
        pregeneration,
        no_pregeneration
    }
    public enum e_CameraPlate
    {
        定位相机平台1,
        定位相机平台2,
        图案相机平台1,
        图案相机平台2,
        检测相机平台1,
        检测相机平台2,

    }
    public enum e_Camera
    {
        定位相机,
        图案相机,
        检测相机
    }

    public class Postion
    {
        public double X { get; set; }
        public double Y { get; set; }
        public double Angle { get; set; }
        public double xMin { get; set; }
        public double xMax { get; set; }
        public double yMax { get; set; }
        public double yMin { get; set; }
        public double rMax { get; set; }
        public double rMin { get; set; }
    }
    [Serializable]
    public class PlateVisionInfo
    {
        /// <summary>
        /// 相机SN码
        /// </summary>
        public string Sn { get; set; }
        /// <summary>
        /// 标定点列表
        /// </summary>
        public List<CalibPoint> CailList { get; set; }
        /// <summary>
        /// 标定数组
        /// </summary>
        public double[] arr_cail { get; set; }
        /// <summary>
        /// 像素标定数组
        /// </summary>
        public double[] arr_pixcail { get; set; }
        /// <summary>
        /// 取料旋转中心X
        /// </summary>
        public double CenterRealX { get; set; }
        /// <summary>
        /// 取料旋转中心Y
        /// </summary>
        public double CenterRealY { get; set; }
        public double Xmin { get; set; }
        /// <summary>
        /// 结果补偿极限值
        /// </summary>
        public double Xmax { get; set; }
        /// <summary>
        /// 结果补偿极限值
        /// </summary>
        public double Ymin { get; set; }
        /// <summary>
        /// 结果补偿极限值
        /// </summary>
        public double Ymax { get; set; }
        /// <summary>
        /// 结果补偿极限值
        /// </summary>
        public double Rmin { get; set; }
        /// <summary>
        /// 结果补偿极限值
        /// </summary>
        public double Rmax { get; set; }
        /// <summary>
        /// 做旋转标定时用的机械坐标
        /// </summary>
        public double CailPointX { get; set; }
        /// <summary>
        /// 做旋转标定时用的机械坐标
        /// </summary>
        public double CailPointY { get; set; }
        public double rorateOffsetX { get; set; }
        public double rorateOffsetY { get; set; }
    }
    [Serializable]
    public class CalibPoint

    {
        /// <summary>
        /// 序号
        /// </summary>
        public int Index { get; set; }
        /// <summary>
        /// 像素X
        /// </summary>
        public float pixX { get; set; }
        /// <summary>
        /// 像素Y
        /// </summary>
        public float pixY { get; set; }
        /// <summary>
        /// 实际X
        /// </summary>
        public float realX { get; set; }
        /// <summary>
        /// 实际Y
        /// </summary>
        public float realY { get; set; }
        public float realR { get; set; }
    }
}
